LeetCode 328. Odd Even Linked List
原题链接在这里: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 }
AC C++:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* oddEvenList(ListNode* head) { 14 if(!head || !head->next || !head->next->next){ 15 return head; 16 } 17 18 ListNode* oddHead = head; 19 ListNode* evenHead = head->next; 20 ListNode* oddCur = oddHead; 21 ListNode* evenCur = evenHead; 22 while(evenCur && evenCur->next){ 23 oddCur->next = oddCur->next->next; 24 evenCur->next = evenCur->next->next; 25 oddCur = oddCur->next; 26 evenCur = evenCur->next; 27 } 28 29 oddCur->next = evenHead; 30 return head; 31 } 32 };
AC Python:
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, val=0, next=None): 4 # self.val = val 5 # self.next = next 6 class Solution: 7 def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 if not head or not head.next or not head.next.next: 9 return head 10 11 oddHead = oddCur = head 12 evenHead = evenCur = head.next 13 while evenCur and evenCur.next: 14 oddCur.next = oddCur.next.next 15 evenCur.next = evenCur.next.next 16 oddCur = oddCur.next 17 evenCur = evenCur.next 18 19 oddCur.next = evenHead 20 return head