码迷,mamicode.com
首页 > 其他好文 > 详细

如何实现链表的逆序

时间:2019-10-19 12:59:21      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:bfc   none   代码实现   描述   int   sel   turn   时间   closed   

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)。

如何实现链表的逆序

标签:bfc   none   代码实现   描述   int   sel   turn   时间   closed   

原文地址:https://www.cnblogs.com/dabric/p/11694446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!