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

链表反转实现

时间:2021-04-21 12:23:41      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:inverse   code   inf   while   list   new   ini   return   空间   

方法一:双指针法

采用就地反转,不用额外开辟空间

注意:接收链表的head节点,返回当前节点

方法二:递归法

代码如下:

class Node(object):
    def __init__(self, item, next=None):
        self.item = item
        self.next = next

def create_linklist_head(li):
    head = Node(li[0])
    for e in li[1:]:
        node = Node(e)
        node.next = head
        head = node
    return head

def create_linklist_tail(li):
    head = Node(li[0])
    tail = head
    for e in li[1:]:
        node = Node(e)
        tail.next = node
        tail = node
    return head

def print_linklist(lk):
    while lk:
        print(lk.item, end=,)
        lk = lk.next

def inverse_linklist(head):
    if head == None or head.next == None:
        return head
    currNode = head
    predNode = None
    while currNode:
        tmp = currNode.next
        currNode.next = predNode
        predNode = currNode
        currNode = tmp
    return predNode

def recursion_inverse_lk(head):
    if head == None or head.next == None:
        return head
    new_head = recursion_inverse_lk(head.next)
    head.next.next = head
    head.next = None
    return new_head


if __name__ == __main__:
    lk = create_linklist_tail([1,2,3,4,5])
    print(原始:)
    print_linklist(lk)
    # res = inverse_linklist(lk)
    res = recursion_inverse_lk(lk)
    print(\n反转:)
    print_linklist(res)

结果展示:

技术图片

 

链表反转实现

标签:inverse   code   inf   while   list   new   ini   return   空间   

原文地址:https://www.cnblogs.com/demo-deng/p/14679133.html

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