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

039 链表的逆置

时间:2021-01-04 11:07:13      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:and   width   src   href   while   str   ons   val   引用   

链表是一个特殊的数据结构,其中每个节点包含自己的数据以及下一个值的引用(指针),链表的逆置就是指将链表下一个值的引用(指针)调换,如下图所示:

技术图片

 

第一步 构造链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Node(object):
 
    def __init__(self, value, next):
        self.value = value
        self.next = next
 
 
head = Node(‘头‘, None)
last = head
for i in range(5):
    node = Node(‘v%s‘ % i, None)
    last.next = node
    last = node
 
# ######### 查看链表关系 ##########
print(‘原始链表信息为:‘)
print(head.value)
print(head.next.value)
print(head.next.next.value)
print(head.next.next.next.value)
print(head.next.next.next.next.value)
print(head.next.next.next.next.next.value)

第二步 链表逆置

实现思路:
技术图片

 

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def reverse_linked_list(head):
    """
    链表逆置
    :param head:
    :return:
    """
    if not head or not head.next:
        return head
 
    prev_node = None
    current_node = head
    next_node = head.next
 
    while True:
        current_node.next = prev_node
        if not next_node:
            break
        prev_node = current_node
        current_node = next_node
        next_node = current_node.next
    return current_node
 
 
new_head = reverse_linked_list(head)
 
print(‘逆置之后的链表‘)
print(new_head.value)
print(new_head.next.value)
print(new_head.next.next.value)
print(new_head.next.next.next.value)
print(new_head.next.next.next.next.value)
print(new_head.next.next.next.next.next.value)

  

 

039 链表的逆置

标签:and   width   src   href   while   str   ons   val   引用   

原文地址:https://www.cnblogs.com/abdm-989/p/14214027.html

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