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)

    结果展示:

    时刻记着自己要成为什么样的人!
  • 相关阅读:
    UVa532 Dungeon Master 三维迷宫
    6.4.2 走迷宫
    UVA 439 Knight Moves
    UVa784 Maze Exploration
    UVa657 The die is cast
    UVa572 Oil Deposits DFS求连通块
    UVa10562 Undraw the Trees
    UVa839 Not so Mobile
    327
    UVa699 The Falling Leaves
  • 原文地址:https://www.cnblogs.com/demo-deng/p/14679133.html
Copyright © 2011-2022 走看看