Python實現反轉鍊錶

2021-10-19 10:48:10 字數 1839 閱讀 4648

將鍊錶進行反轉

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

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

其實**的實現原理很簡單,只需要按照下面幾個步驟即可實現鍊錶的反**

儲存上乙個節點的節點資訊

繼續處理後面的節點

class

listnode

:def

__init__

(self,val,

next

=none):

ifisinstance

(val,

int)

: self.val = val

self.

next

=next

elif

isinstance

(val,

list):

self.val = val[0]

self.

next

=none

head = self

for i in

range(1

,len

(val)):

node = listnode(val[i]

) head.

next

= node

head = head.

next

class

solution

:def

reverselist

(self, head: listnode)

-> listnode:

#用來記錄上乙個節點

prev =

none

#儲存當前的鍊錶

curr = head

while curr !=

none

:#記錄後乙個節點

nex = curr.

next

#改變節點的指向,反轉鍊錶

curr.

next

= prev

prev = curr

#繼續處理後面的鍊錶

curr = nex

return prev

l =[1,

2,3,

4,5]

list_node = listnode(l)

obj = solution(

)reve_list_node = obj.reverselist(list_node)

while reve_list_node:

print

(reve_list_node.val)

reve_list_node = reve_list_node.

next

class

solution

:def

reverselist

(self, head: listnode)

-> listnode:

if head ==

none

or head.

next

==none

:return head

#繼續遞迴後乙個節點

newhead = self.reverselist(head.

next

)#反轉節點

head.

next

.next

= head

head.

next

=none

return newhead

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

python 鍊錶反轉

definition of listnode class listnode object def init self,val,next none self.val val self.next next class solution param node n return the new head o...