• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input. 
The first node is considered odd, the second node even and so on ...

给odd序列和even序列各设置一个dummy head

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode oddEvenList(ListNode head) {
11         if (head==null || head.next==null || head.next.next==null) return head;
12         ListNode oddDummyHead = new ListNode(-1);
13         ListNode evenDummyHead = new ListNode(-1);
14         oddDummyHead.next = head;
15         evenDummyHead.next = head.next;
16         ListNode oddCur = head;
17         ListNode evenCur = head.next;
18         while (evenCur!=null && evenCur.next!=null) {
19             oddCur.next = evenCur.next;
20             evenCur.next = evenCur.next.next;
21             oddCur = oddCur.next;
22             evenCur = evenCur.next;
23         }
24         oddCur.next = evenDummyHead.next;
25         return oddDummyHead.next;
26     }
27 }

 

posted @ 2016-01-18 03:59  neverlandly  阅读(1742)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3