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.
https://leetcode.com/problems...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, head: ListNode) -> ListNode: # If zero, one or two elements, then solved if head == None or head.next == None or head.next.next == None: return head # Two pointers p = head n = head.next t = None while n.next: # If there is even element if n.next.next: # Keep it for now for both n and p t = n.next.next m = p.next p.next = n.next p = p.next # Recover link for p and n p.next = m n.next = t n = n.next else: # Save and insert odd t = p.next p.next = n.next p = p.next p.next = t n.next = None return head
文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/43625.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...
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 ...
摘要:給定一個單鏈表,把所有的奇數(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é)點的值的奇偶性。 請嘗試使用原地算法完成...
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...
閱讀 3670·2021-09-07 09:59
閱讀 725·2019-08-29 15:12
閱讀 811·2019-08-29 11:14
閱讀 1316·2019-08-26 13:27
閱讀 2671·2019-08-26 10:38
閱讀 3140·2019-08-23 18:07
閱讀 1282·2019-08-23 14:40
閱讀 1932·2019-08-23 12:38