原题链接在这里:https://leetcode.com/problems/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
.
题解:
要归类的是node的index而不是node的value. 双指针, 一个指向odd位置, 一个指向even位置.
Time Complexity: O(n). Space: O(1).
AC Java:
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){ 12 return head; 13 } 14 ListNode oddHead = head; 15 ListNode evenHead = head.next; 16 ListNode oddCur = oddHead; 17 ListNode evenCur = evenHead; 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 = evenHead; 25 return oddHead; 26 } 27 }