Leet Code OJ 328. Odd Even Linked List [Difficulty: Easy]
題目:
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 …
翻譯:
給定一個單鏈表,把所有的奇數節點放到一起,所有的偶數節點放到單數節點的后面。請注意這里我們討論的是節點的編號的奇數偶數,而不是節點的值。
你應該直接在鏈表上去做。這個程序應該運行在O(1)的空間復雜度和O(節點數)的時間復雜度。
提示:這些奇數偶數區域中相關聯的前后順序,應該和輸入的時候一樣。第一個節點作為奇數節點,第二個作為偶數節點,由此類推。。。
分析:
本題比較容易出錯的地方,第一個是看錯題目,把編號的奇偶數看成節點值的奇偶數;第二個是移動節點時,對于next指針的處理上。如果沒有把next正確指向,有可能把鏈表變成循環列表,這個時候就會出現“Memory Limit Exceeded”這樣的錯誤了。下面的代碼創建了多個臨時變量,把奇數偶數節點分開為2個鏈表,最后再合并的做法,也是為了代碼清晰易讀,其實是可以有更精簡的寫法的,歡迎讀者補充。
代碼:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/ public class Solution {public ListNode oddEvenList(ListNode head) {ListNode oddFirstNode = new ListNode(0);ListNode oddCurrentNode = oddFirstNode;ListNode evenFirstNode = new ListNode(0);ListNode evenCurrentNode = evenFirstNode;int count=1;while (head != null) {ListNode temp=head.next;if (count% 2 == 1) {oddCurrentNode.next=head;oddCurrentNode=head;} else {evenCurrentNode.next=head;evenCurrentNode=head;}head.next=null;head = temp;count++;}oddCurrentNode.next=evenFirstNode.next;return oddFirstNode.next;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 328. Odd Even Linked List [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 268. Mi
- 下一篇: Leet Code OJ 189. Ro