zoukankan      html  css  js  c++  java
  • 链表反转实现

    方法一:双指针法

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

    注意:接收链表的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('
    反转:')
        print_linklist(res)

    结果展示:

    时刻记着自己要成为什么样的人!
  • 相关阅读:
    CentOS之文件搜索命令locate
    CentOs之链接命令
    CentOs之常见目录作用介绍
    centOs之目录处理命令
    Query注解及方法限制
    Repository接口
    OkHttp和Volley对比
    Base64加密与MD5的区别?
    支付宝集成
    Android 中 非对称(RSA)加密和对称(AES)加密
  • 原文地址:https://www.cnblogs.com/demo-deng/p/14679133.html
Copyright © 2011-2022 走看看