Given the head
of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1)
extra space complexity and O(n)
time complexity.
Example 1:
Input: head = [1,2,3,4,5] Output: [1,3,5,2,4]
Example 2:
Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4]
Constraints:
- The number of nodes in the linked list is in the range
[0, 104]
. -106 <= Node.val <= 106
SOL:
我用兩個ListNode來分別記錄與連接odd nodes, even nodes,最後把even接到odd.next即可。
一開始用直覺寫程式碼,結果串成一個環。
原來是odd跟even都會接到最後一個node 5,所以要讓even最後的node是None。
不過這樣並不足以解完全部,提交之後會有以下錯誤,有用到head.next, head.next.next 的部分,都必須考慮前一個node(head, head.next)是否會為空,因為空的話就不會有next。
最終程式碼長這樣:
參考一下別人更簡潔的程式碼:Leetcode — 328. Odd Even Linked List (中文)
留言列表