LeetCode-Odd Even Linked List

LiBlog發表於2016-08-07

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 ...

Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.

Solution:

 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) return head;
12         
13         ListNode preHead = new ListNode(-1);
14         preHead.next = head;
15         
16         ListNode oddEnd = head;
17         ListNode evenEnd = head.next;
18         
19         while (evenEnd!=null && evenEnd.next!=null){
20             ListNode target = evenEnd.next;
21             evenEnd.next = evenEnd.next.next;
22             target.next = oddEnd.next;
23             oddEnd.next = target;
24             oddEnd = oddEnd.next;
25             evenEnd = evenEnd.next;
26         }
27         
28         return preHead.next;
29     }
30 }

 

相關文章