国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python數據結構之翻轉鏈表

2020-02-23 04:23:25
字體:
來源:轉載
供稿:網友

翻轉一個鏈表

樣例:給出一個鏈表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 

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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 和政县| 广德县| 宜川县| 平和县| 石台县| 彭州市| 凤台县| 尼勒克县| 九龙城区| 东兰县| 石城县| 南澳县| 平远县| 泗水县| 黄冈市| 旅游| 大宁县| 宣威市| 娄烦县| 南乐县| 四会市| 金门县| 沭阳县| 永修县| 贡觉县| 南汇区| 永泰县| 建水县| 黔东| 酒泉市| 五常市| 余江县| 陵川县| 祁阳县| 宜春市| 桂阳县| 同江市| 定陶县| 张家界市| 永福县| 新龙县|