1. 程式人生 > 程式設計 >用python介紹4種常用的單鏈表翻轉的方法小結

用python介紹4種常用的單鏈表翻轉的方法小結

如何把一個單鏈表進行反轉?

方法1:將單鏈表儲存為陣列,然後按照陣列的索引逆序進行反轉。

方法2:使用3個指標遍歷單鏈表,逐個連結點進行反轉。

方法3:從第2個節點到第N個節點,依次逐節點插入到第1個節點(head節點)之後,最後將第一個節點挪到新表的表尾。

方法4: 遞迴(相信我們都熟悉的一點是,對於樹的大部分問題,基本可以考慮用遞迴來解決。但是我們不太熟悉的一點是,對於單鏈表的一些問題,也可以使用遞迴。可以認為單鏈表是一顆永遠只有左(右)子樹的樹,因此可以考慮用遞迴來解決。或者說,因為單鏈表本身的結構也有自相似的特點,所以可以考慮用遞迴來解決)

開闢輔助陣列,新建表頭反轉,就地反轉,遞迴反轉

# -*- coding: utf-8 -*-
'''
連結串列逆序
'''
class ListNode: 
  def __init__(self,x): 
    self.val=x
    self.next=None
 
'''
第一種方法:
對於一個長度為n的單鏈表head,用一個大小為n的陣列arr儲存從單鏈表從頭
到尾遍歷的所有元素,在從arr尾到頭讀取元素簡歷一個新的單鏈表
時間消耗O(n),空間消耗O(n)
'''   
def reverse_linkedlist1(head):
  if head == None or head.next == None: #邊界條件
    return head
  arr = [] # 空間消耗為n,n為單鏈表的長度
  while head:
    arr.append(head.val)
    head = head.next
  newhead = ListNode(0)
  tmp = newhead
  for i in arr[::-1]:
    tmp.next = ListNode(i)
    tmp = tmp.next
  return newhead.next
 
'''
開始以單鏈表的第一個元素為迴圈變數cur,並設定2個輔助變數tmp,儲存資料;
newhead,新的翻轉連結串列的表頭。
時間消耗O(n),空間消耗O(1)
'''
 
def reverse_linkedlist2(head):
  if head == None or head.next == None: #邊界條件
    return head
  cur = head #迴圈變數
  tmp = None #儲存資料的臨時變數
  newhead = None #新的翻轉單鏈表的表頭
  while cur:
    tmp = cur.next
    cur.next = newhead
    newhead = cur  # 更新 新連結串列的表頭
    cur = tmp
  return newhead
   
'''
開始以單鏈表的第二個元素為迴圈變數,用2個變數迴圈向後操作,並設定1個輔助變數tmp,儲存資料;
時間消耗O(n),空間消耗O(1)
'''
 
 
def reverse_linkedlist3(head):
  if head == None or head.next == None: #邊界條件
    return head
  p1 = head #迴圈變數1
  p2 = head.next #迴圈變數2
  tmp = None #儲存資料的臨時變數
  while p2:
    tmp = p2.next
    p2.next = p1
    p1 = p2
    p2 = tmp
  head.next = None
  return p1
 
'''
遞迴操作,先將從第一個點開始翻轉轉換從下一個節點開始翻轉
直至只剩一個節點
時間消耗O(n),空間消耗O(1)
'''
 
def reverse_linkedlist4(head):
  if head is None or head.next is None:
    return head
  else:
    newhead=reverse_linkedlist4(head.next)
    head.next.next=head
    head.next=None
  return newhead
 
     
def create_ll(arr):
  pre = ListNode(0)
  tmp = pre
  for i in arr:
    tmp.next = ListNode(i)
    tmp = tmp.next
  return pre.next
   
def print_ll(head):
  tmp = head
  while tmp:
    print tmp.val
    tmp=tmp.next
 
a = create_ll(range(5))
print_ll(a) # 0 1 2 3 4
a = reverse_linkedlist1(a)
print_ll(a) # 4 3 2 1 0
a = reverse_linkedlist2(a)
print_ll(a) # 0 1 2 3 4
a = reverse_linkedlist3(a)
print_ll(a) # 4 3 2 1 0
a = reverse_linkedlist4(a)
print_ll(a) # 0 1 2 3 4

到此這篇關於用python介紹4種常用的單鏈表翻轉的方法小結的文章就介紹到這了,更多相關python 單鏈表翻轉內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!