如何實現鏈表的逆序


1 單向鏈表的反轉

問題描述:

  給定一個帶頭結點的單鏈表,請將其逆序。即如果單鏈表原來為head -->1 --> 2 --> 3 --> 4 --> 5,那么逆序后變為head --> 5 --> 4 --> 3 --> 2 --> 1。

解決過程:

  給定一個單向鏈表1-->2-->3,通過下面的示意圖,看如何一步一步的將單向列表反轉。

 

 

 代碼實現:

 1 class Node(object):
 2     def __init__(self, data):
 3         self.data = data
 4         self.next = None
 5 
 6 def createSingleLink():
 7     head = Node(1)
 8     cur = head
 9     for i in range(2, 10):
10         cur.next = Node(i)
11         cur = cur.next
12     return head
13 
14 def printSingleLink(head):
15     cur = head
16     while cur is not None:
17         print(cur.data, end='')
18         if cur.next is not None:
19             print("-->", end='')
20         cur = cur.next
21 
22 def Reverse(head):
23     pre = None
24     cur = head
25     while cur is not None:
26         next_ = cur.next
27         cur.next = pre
28         pre = cur
29         cur = next_
30     return pre
31 
32 if __name__ == '__main__':
33     singleHead = createSingleLink()
34     printSingleLink(singleHead)
35     reverSingleHead = Reverse(singleHead)
36     print()
37     printSingleLink(reverSingleHead)
View Code

2 雙向鏈表反轉

問題描述:

  給定一個帶頭結點的雙向鏈表,請將其逆序。即如果單鏈表原來為head -->1 --> 2 --> 3 --> 4 --> 5,那么逆序后變為head --> 5 --> 4 --> 3 --> 2 --> 1。

解決過程:

  例如,給定一個帶頭結點的雙向鏈表1-->2-->3,如下圖看如何一步一步進行反轉:

代碼實現:

 1 class Node(object):
 2     def __init__(self, data):
 3         self.last = None
 4         self.data = data
 5         self.next = None
 6 
 7 def creatDoubleLink():
 8     head = Node(1)
 9     cur = head
10     for i in range(2, 10):
11         cur.next = Node(i)
12         Node(i).last = cur
13         cur = cur.next
14     return head
15 
16 def printDoubleLink(head):
17     cur = head
18     while cur:
19         print(cur.data, end='')
20         if cur.next:
21             print("-->", end='')
22         cur = cur.next
23 
24 def Reverse(head):
25     pre = None
26     cur = head
27     next_ = None
28     while cur:
29         next_ = cur.next
30         cur.next = pre
31         cur.last = next_
32         pre = cur
33         cur = next_
34     return pre
35     
36 if __name__ == '__main__':
37     doubleHead = creatDoubleLink()
38     printDoubleLink(doubleHead)
39     reveDoubleHead = Reverse(doubleHead)
40     print()
41     printDoubleLink(reveDoubleHead)
View Code

3 總結:

  單向鏈表和雙向鏈表的反轉比較簡單,只需做到代碼一次成型,運行不出錯即可。上述兩種代碼的實現過程,都是對原有的鏈表進行遍歷,所以如果鏈表長度為N,那么它們的時間復雜度和空間復雜度為O(N)和O(1)。


免責聲明!

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



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