日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python数据结构之链表_Python数据结构之翻转链表

發布時間:2025/3/15 python 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python数据结构之链表_Python数据结构之翻转链表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

翻轉一個鏈表

樣例:給出一個鏈表1->2->3->null,這個翻轉后的鏈表為3->2->1->null

一種比較簡單的方法是用“摘除法”。就是先新建一個空節點,然后遍歷整個鏈表,依次令遍歷到的節點指向新建鏈表的頭節點。

那樣例來說,步驟是這樣的:

1. 新建空節點:None

2. 1->None

3. 2->1->None

4. 3->2->1->None

代碼就非常簡單了:

"""

Definition of ListNode

class ListNode(object):

def __init__(self, val, next=None):

self.val = val

self.next = next

"""

class Solution:

"""

@param head: The first node of the linked list.

@return: You should return the head of the reversed linked list.

Reverse it in-place.

"""

def reverse(self, head):

temp = None

while head:

cur = head.next

head.next = temp

temp = head

head = cur

return temp

# write your code here

當然,還有一種稍微難度大一點的解法。我們可以對鏈表中節點依次摘鏈和鏈接的方法寫出原地翻轉的代碼:

"""

Definition of ListNode

class ListNode(object):

def __init__(self, val, next=None):

self.val = val

self.next = next

"""

class Solution:

"""

@param head: The first node of the linked list.

@return: You should return the head of the reversed linked list.

Reverse it in-place.

"""

def reverse(self, head):

if head is None:

return head

dummy = ListNode(-1)

dummy.next = head

pre, cur = head, head.next

while cur:

temp = cur

# 把摘鏈的地方連起來

pre.next = cur.next

cur = pre.next

temp.next = dummy.next

dummy.next = temp

return dummy.next

# write your code here

需要注意的是,做摘鏈的時候,不要忘了把摘除的地方再連起來

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

更多Python數據結構之翻轉鏈表相關文章請關注PHP中文網!

本條技術文章來源于互聯網,如果無意侵犯您的權益請點擊此處反饋版權投訴

本文系統來源:php中文網

總結

以上是生活随笔為你收集整理的python数据结构之链表_Python数据结构之翻转链表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。