链表的逆置
链表是一个特殊的数据结构,其中每个节点包含自己的数据以及下一个值的引用(指针),链表的逆置就是指将链表下一个值的引用(指针)调换,如下图所示:
链表的节点的结构如下:
data为自定义的数据,next为下一个节点的地址
一 构造链表
class Node(object): def __init__(self, value, next): self.value = value self.next = next head = Node('头', None) last = head l = ['涉哥', '刚哥', '雷哥', '强哥'] for i in l: node = Node('%s' % i, None) last.next = node last = node # ######### 查看链表关系 ########## print('原始链表信息为%s'%head.value) print(head.next.value) print(head.next.next.value) print(head.next.next.next.value) print(head.next.next.next.next.value)
第二步 链表逆置
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)