Python 鍊錶的實現和反轉

2021-10-04 11:05:21 字數 988 閱讀 5399

# coding=utf-8

"""question:

有乙個單向鍊錶,請編寫乙個函式,將這個單向鍊錶反轉,並返回反轉後的頭節點

"""# 節點類

class node:

def __init__(self, val):

self.val = val

self.next = none

# 反轉鍊錶

def reverse_link(header):

if not header or not header.next:

return header

pre = none # 存放上乙個節點

cur = header # 存放當前節點

while cur:

tmp = cur.next

cur.next = pre

pre = cur

cur = tmp

return pre

# 將鍊錶元素按序儲存在列表中

def link2list(header):

cur = header

l =

while cur:

cur = cur.next

return l

if __name__ == '__main__':

node0 = node(0)

node1 = node(1)

node2 = node(2)

node3 = node(3)

node4 = node(4)

node0.next = node1

node1.next = node2

node2.next = node3

node3.next = node4

# 測試

print(link2list(node0))

print(link2list(reverse_link(node0)))

Python實現反轉鍊錶

將鍊錶進行反轉 輸入 1 2 3 4 5 null 輸出 5 4 3 2 1 null 其實 的實現原理很簡單,只需要按照下面幾個步驟即可實現鍊錶的反 儲存上乙個節點的節點資訊 繼續處理後面的節點 class listnode def init self,val,next none ifisinst...

leetcode 反轉鍊錶 python實現

題目 給定乙個單鏈表和煉表首節點,要求反轉鍊錶 解題思路 反轉相鄰的兩個節點 definition for singly linked list.class listnode def init self,x self.val x self.next none class solution def r...

python實現鍊錶與反轉

鍊錶記錄了頭節點與尾節點,是為了方便末尾新增時,不在遍歷鍊錶而設定的。反轉的思想是設定乙個前驅節點為none,首節點指向none,下乙個節點指向前乙個節點即可。class node object def init self,data none next none self.data data sel...