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

1.1链表逆序

时间:2019-09-04 13:50:16      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:ext   head   int   ini   for   ever   init   coding   ==   

链表逆序

有头结点的链表逆序

# -*-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链表逆序

标签:ext   head   int   ini   for   ever   init   coding   ==   

原文地址:https://www.cnblogs.com/miao-study/p/11458407.html

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