leetcode 328 奇偶鍊錶

2021-09-28 19:20:02 字數 3063 閱讀 1775

title: leetcode-328 | 奇偶鍊錶

date: 2019-5-4 18:28:26

comments: true

categories: 「leetcode」

tags:

- leetcode 中等難度

- 鍊錶

給定乙個單鏈表,把所有的奇數節點和偶數節點分別排在一起。請注意,這裡的奇數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。

請嘗試使用原地演算法完成。你的演算法的空間複雜度應為 o(1),時間複雜度應為 o(nodes),nodes 為節點總數。

示例 1:

輸入: 1->2->3->4->5->null

輸出: 1->3->5->2->4->null

示例 1:

輸入: 2->1->3->5->6->4->7->null

輸出: 2->3->6->7->1->5->4->null

說明:

應當保持奇數節點和偶數節點的相對順序。

鍊錶的第乙個節點視為奇數節點,第二個節點視為偶數節點,以此類推。

不妨取資料到列表中,然後根據題意操作,然後構成資料格式

和上一道題(86)類似

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

class

solution

(object):

defoddevenlist

(self, head)

:"""

:type head: listnode

:rtype: listnode

"""#空結點或者乙個節點,直接返回

if head==

none

or head.

next

==none

:return head

virtualhead = listnode(0)

odd =

even =

p = head

i =1while p:

if i%2==

0:else

: i+=

1 p = p.

next

t = odd+even

p = virtualhead

for i in t:

p.next

= i p = p.

next

p.next

=none

return virtualhead.

next

結果:

執行用時 : 48 ms, 在odd even linked list的python提交中擊敗了92.31% 的使用者

記憶體消耗 : 15.3 mb, 在odd even linked list的python提交中擊敗了6.37% 的使用者

提交時間

狀態執行用時

記憶體消耗

語言幾秒前

通過48 ms

15.3mb

python

## 優化 不必建立列表儲存,直接加入

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

class

solution

(object):

defoddevenlist

(self, head)

:"""

:type head: listnode

:rtype: listnode

"""#空結點或者乙個節點,直接返回

if head==

none

or head.

next

==none

:return head

odd = listnode(0)

oddh = odd #指標

even = listnode(0)

evenh = even #指標

p = head #指標

i =1while p:

if i%2==

0:evenh.

next

= p evenh = evenh.

next

else

: oddh.

next

= p oddh = oddh.

next

i +=

1 p = p.

next

oddh.

next

= evenh.

next

=none

oddh.

next

= even.

next

return odd.

next

結果:

執行用時 : 48 ms, 在odd even linked list的python提交中擊敗了92.31% 的使用者

記憶體消耗 : 15.1 mb, 在odd even linked list的python提交中擊敗了29.21% 的使用者

提交時間

狀態執行用時

記憶體消耗

語言幾秒前

通過48 ms

15.1mb

python

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 ...