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


這里給出了4種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

 

本文轉載自:https://blog.csdn.net/u011452172/article/details/78127836 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM