最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python數(shù)據(jù)結(jié)構(gòu)之翻轉(zhuǎn)鏈表

 更新時間:2017年02月25日 08:37:23   投稿:lqh  
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)之翻轉(zhuǎn)鏈表的相關(guān)資料,需要的朋友可以參考下

翻轉(zhuǎn)一個鏈表

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

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

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

1. 新建空節(jié)點: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 

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

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

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

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

相關(guān)文章

最新評論

葵青区| 镇原县| 利津县| 绥阳县| 图木舒克市| 正镶白旗| 兴文县| 西华县| 吴江市| 永吉县| 石屏县| 慈溪市| 九龙坡区| 通化市| 南雄市| 田东县| 姚安县| 辽中县| 鄂伦春自治旗| 黑山县| 宁乡县| 儋州市| 潼关县| 土默特右旗| 莲花县| 凤庆县| 蒙山县| 思南县| 白水县| 弥渡县| 石河子市| 建阳市| 绥棱县| 富裕县| 江源县| 东辽县| 屏边| 游戏| 出国| 铜梁县| 蕉岭县|