Problem
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 1:
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->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 ...
class Solution { public ListNode oddEvenList(ListNode head) { if (head == null) return head; ListNode odd = head, even = head.next, evenHead = even; while (even != null && even.next != null) { odd.next = odd.next.next; even.next = even.next.next; odd = odd.next; even = even.next; } odd.next = evenHead; return head; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/73017.html
摘要:最后將奇數(shù)鏈表尾連到偶數(shù)鏈表頭即可。改進的思路在于減少額外的變量創(chuàng)建。奇數(shù)指針的初始值為,而偶數(shù)指針的初始值為。則下一個奇數(shù)值位于上,此時將該奇數(shù)指針移動到上之后,偶數(shù)指針的值則為。 題目要求 Given a singly linked list, group all odd nodes together followed by the even nodes. Please note...
摘要:給定一個單鏈表,把所有的奇數(shù)節(jié)點和偶數(shù)節(jié)點分別排在一起。鏈表的第一個節(jié)點視為奇數(shù)節(jié)點,第二個節(jié)點視為偶數(shù)節(jié)點,以此類推。需要記錄偶數(shù)位節(jié)點的第一個節(jié)點,因為這是偶數(shù)鏈表的頭節(jié)點,最后拼接鏈表時要用奇數(shù)鏈表的尾節(jié)點連接該節(jié)點。 ?給定一個單鏈表,把所有的奇數(shù)節(jié)點和偶數(shù)節(jié)點分別排在一起。請注意,這里的奇數(shù)節(jié)點和偶數(shù)節(jié)點指的是節(jié)點編號的奇偶性,而不是節(jié)點的值的奇偶性。 請嘗試使用原地算法完成...
摘要:給定一個單鏈表,把所有的奇數(shù)節(jié)點和偶數(shù)節(jié)點分別排在一起。鏈表的第一個節(jié)點視為奇數(shù)節(jié)點,第二個節(jié)點視為偶數(shù)節(jié)點,以此類推。需要記錄偶數(shù)位節(jié)點的第一個節(jié)點,因為這是偶數(shù)鏈表的頭節(jié)點,最后拼接鏈表時要用奇數(shù)鏈表的尾節(jié)點連接該節(jié)點。 ?給定一個單鏈表,把所有的奇數(shù)節(jié)點和偶數(shù)節(jié)點分別排在一起。請注意,這里的奇數(shù)節(jié)點和偶數(shù)節(jié)點指的是節(jié)點編號的奇偶性,而不是節(jié)點的值的奇偶性。 請嘗試使用原地算法完成...
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 notthe value in the nodes.You should try to do it in plac...
Problem 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. Example Example:Given...
閱讀 1748·2023-04-25 16:28
閱讀 684·2021-11-23 09:51
閱讀 1467·2019-08-30 15:54
閱讀 1149·2019-08-30 15:53
閱讀 2816·2019-08-30 15:53
閱讀 3413·2019-08-30 15:43
閱讀 3250·2019-08-30 11:18
閱讀 3262·2019-08-26 10:25