leetcode328 奇偶鍊錶

2021-09-20 21:19:43 字數 1608 閱讀 8610

思路:

例如:1,2,3,4,5,null

每次將偶下標後的奇下標插入到上乙個奇下標之後,然後注意連線奇部分和偶部分即可。

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

class solution(object):

def oddevenlist(self, head):

""":type head: listnode

:rtype: listnode

"""if head==none or head.next==none:#空鍊錶 或 只有乙個元素的鍊錶

return head

#head為奇煉表頭結點,o為奇鍊錶尾結點

o=head

#p為偶煉表頭結點,e為偶煉表尾結點

e=p=head.next

while o.next!=none and e.next!=none:

o.next=e.next

o=o.next

e.next=o.next

e=e.next

o.next=p

return head

我一開始寫複雜了:

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

class solution(object):

def oddevenlist(self, head):

""":type head: listnode

:rtype: listnode

"""#使用兩個變數:

#oddtail:當前奇數的尾結點

#i:記錄當前遍歷到的結點下標,奇數就需要插到oddtail後,偶數就繼續遍歷

#1,oddtail:3,2,pre:4,tail:5,6

if head==none:#空鍊錶

return head

if head.next==none:#乙個元素的鍊錶

return head

oddtail=pre=tail=head

even=head.next

i=1while tail!=none:

if i%2==1 and i!=1:

pre.next=tail.next

tail.next=even

oddtail.next=tail

oddtail=oddtail.next

tail=pre.next

i+=1

else:

pre=tail

tail=tail.next

i+=1

return head

LeetCode 328 奇偶鍊錶

給定乙個單鏈表,把所有的奇數節點和偶數節點分別排在一起。請注意,這裡的奇數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。請嘗試使用原地演算法完成。你的演算法的空間複雜度應為 o 1 時間複雜度應為 o nodes nodes 為節點總數。示例 1 輸入 1 2 3 4 5 null ...

LeetCode 328 奇偶鍊錶

給定乙個單鏈表,把所有的奇數節點和偶數節點分別排在一起。請注意,這裡的奇數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。請嘗試使用原地演算法完成。你的演算法的空間複雜度應為 o 1 時間複雜度應為 o nodes nodes 為節點總數。示例 1 輸入 1 2 3 4 5 null輸...

Leetcode328 奇偶鍊錶

給定乙個單鏈表,把所有的奇數節點和偶數節點分別排在一起。請注意,這裡的奇數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。請嘗試使用原地演算法完成。你的演算法的空間複雜度應為 o 1 時間複雜度應為 o nodes nodes 為節點總數。示例 1 輸入 1 2 3 4 5 null ...