1.1链表逆序

Posted miao-study

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1.1链表逆序相关的知识,希望对你有一定的参考价值。

链表逆序

有头结点的链表逆序

# -*-coding:utf-8-*-
# 有头结点的链表逆序
class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


def print_link(head):
    cur = head.next
    while cur.next != None:
        print(cur.data, end=' ')
        cur = cur.next
    print(cur.data)


def con_link(n):
    head = Node()
    cur = head
    for i in range(n):
        node = Node(i)
        cur.next = node
        cur = node
    print_link(head)
    reverse_link(head)

def reverse_link(head):
    if head.next == None or head == None:
        return
    pre = head.next
    cur = head.next.next
    pre.next = None
    while cur.next != None:
        next = cur.next
        cur.next = pre
        pre = cur
        cur = next
    cur.next = pre
    head.next = cur
    print_link(head)



if __name__ == '__main__':
    con_link(5)

无头结点的链表逆序

# -*-coding:utf-8-*-
class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next


def print_link(head):
    cur = head
    while cur.next != None:
        print(cur.data, end=' ')
        cur = cur.next
    print(cur.data)


def con_link(n):
    head = Node(0)
    cur = head
    for i in range(1, n):
        node = Node(i)
        cur.next = node
        cur = node
    print_link(head)
    reverse_link(head)

def reverse_link(head):
    if head == None:
        return
    pre = head
    cur = head.next
    pre.next = None
    while cur.next != None:
        next = cur.next
        cur.next = pre
        pre = cur
        cur = next
    cur.next = pre
    head = cur
    print_link(head)

if __name__ == '__main__':
    con_link(10)

以上是关于1.1链表逆序的主要内容,如果未能解决你的问题,请参考以下文章

算法--链表的K逆序问题

链表逆序

数据结构实验之链表二:逆序建立链表

链表逆序

链表的创建逆序打印

--逆序创建链表及链表反转