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

第一步 构造链表
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | classNode(object):    def__init__(self, value, next):        self.value =value        self.next=nexthead =Node('头', None)last =headfori inrange(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 | defreverse_linked_list(head):    """    链表逆置    :param head:    :return:    """    ifnothead ornothead.next:        returnhead    prev_node =None    current_node =head    next_node =head.next    whileTrue:        current_node.next=prev_node        ifnotnext_node:            break        prev_node =current_node        current_node =next_node        next_node =current_node.next    returncurrent_nodenew_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) | 

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号