日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python實現(xiàn)單鏈表中元素的反轉_python

作者:bebr ? 更新時間: 2022-06-28 編程語言

給定一個單鏈表,將其反轉。其實很容易想到,只需要修改每個結點的指針指向:即令后一個結點指向前一個結點,并且將表頭指針指向最后一個結點即可。

這個過程可以用循環(huán)實現(xiàn),也可以用遞歸來實現(xiàn)。

1、用循環(huán)來實現(xiàn):

class LNode:
? ? def __init__(self, elem):
? ? ? ? self.elem = elem
? ? ? ? self.pnext = None
?
def reverse(head):
? ? if head is None or head.pnext is None: #如果輸入的鏈表是空或者只有一個結點,直接返回當前結點
? ? ? ? return head
? ? pre = None #用來指向上一個結點
? ? cur = newhead = head #cur是當前的結點。newhead指向當前新的頭結點
? ? while cur:
? ? ? ? newhead = cur
? ? ? ? temp = cur.pnext
? ? ? ? cur.pnext = pre #將當前的結點的指針指向前一個結點
? ? ? ? pre = cur
? ? ? ? cur = temp
? ? return newhead
?
if __name__=="__main__":
? ? head = LNode(1)
? ? p1 = LNode(2)
? ? p2 = LNode(3)
? ? head.pnext = p1
? ? p1.pnext = p2
? ? p = reverse(head)
? ? while p:
? ? ? ? print(p.elem)
? ? ? ? p = p.pnext

2、用遞歸來實現(xiàn):

class LNode:
? ? def __init__(self, elem):
? ? ? ? self.elem = elem
? ? ? ? self.pnext = None
?
def reverse(head):
? ? if not head or not head.pnext:
? ? ? ? return head
? ? else:
? ? ? ? newhead = reverse(head.pnext)
? ? ? ? head.pnext.pnext = head #令下一個結點的指針指向當前結點
? ? ? ? head.pnext = None #斷開當前結點與下一個結點之間的指針指向聯(lián)系,令其指向空
? ? ? ? return newhead
?
?
if __name__=="__main__":
? ? head = LNode(1)
? ? p1 = LNode(2)
? ? p2 = LNode(3)
? ? head.pnext = p1
? ? p1.pnext = p2
? ? p = reverse(head)
? ? while p:
? ? ? ? print(p.elem)
? ? ? ? p = p.pnext

以下是圖解遞歸的詳細過程:

原文鏈接:https://blog.csdn.net/qq_34840129/article/details/80776363

欄目分類
最近更新