链表:头插法实现逆序

#!/usr/bin/env python
# coding: utf-8

"""
实现链表的逆序
给定一个带头节点的单链表,将其逆序。
head->1->2->3->4->5
变为
head->5->4->3->2->1

https://www.bilibili.com/video/BV1AD4y1d7LX?from=search&seid=9167067349614497192
"""


# 定义链表的节点类
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val    # 节点中存储的数据
        self.next = next  # 指向下一个节点的指针


# 反转链表
def reverse_list_node(head):
    temp = ListNode()  #临时头结点
    while head != None:
        next = head.next       # 备份 head的next
        head.next = temp.next  # 修改 head的next 指向temp后的节点
        temp.next = head       # 插入 将temp后插入head指向的节点
        head = next            # 移动 head,存储next备份的节点
    return temp.next  # 返回temp后的第一个节点


# 打印链表
def print_list_node(head,title):
    print(f"----- {title} -----")
    if head == None:
        print("NULL")
        return
    while head != None:
        print(head.val,end="")
        head = head.next
    print("")

if __name__ == '__main__':
    # 构造节点
    a = ListNode(1)
    b = ListNode(2)
    c = ListNode(3)
    d = ListNode(4)
    e = ListNode(5)
    # 连接节点
    a.next = b
    b.next = c
    c.next = d
    d.next = e

    print_list_node(a, "原始链表")

    # 反转链表
    head = reverse_list_node(a)
    print_list_node(head, "逆序链表")




已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:C马雯娟 返回首页