zoukankan      html  css  js  c++  java
  • Sword_Offer 从尾到头打印链表[6]

    Sword_Offer 从尾到头打印链表[6]

    0x00 题目描述

    题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值

    0x01 解题思路

    方法1:使用栈

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    # Author LQ6H
    
    class ListNode:
        def __init__(self,val):
            self.data=val
            self.next=None
    
    class Solution:
        def PrintListReversingly_Iteratively(self,head):
            """
            :param head: ListNode
            :return: List[int]
            """
            if not head:
                return
            
            stack=[]
    
            p=None
            p=head
    
            while p!=None:
                stack.append(p.data)
                p=p.next
    
            res=[]
            while stack:
                res.append(stack[-1])
                stack.pop()
    
            return res
    

    或者直接反转

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    # Author LQ6H
    
    class ListNode:
        def __init__(self,val):
            self.data=val
            self.next=None
    
    class Solution:
        def PrintListReversingly_Iteratively(self,head):
            """
            :param head: ListNode
            :return: List[int]
            """
            if not head:
                return
            
            stack=[]
    
            p=None
            p=head
    
            while p!=None:
                stack.append(p.data)
                p=p.next
    
            return stack[::-1]
    

    方法二迭代

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    # Author LQ6H
    
    class ListNode:
        def __init__(self,val):
            self.data=val
            self.next=None
    
    class Solution:
        def PrintListReversingly_Recursively(self,head):
            """
            :param head: ListNode
            :return: List[int]
            """
            if not head:
                return
    
            self.res=[]
    
            if head.next!=None:
                self.PrintListReversingly_Recursively(head.next)
    
            self.res.append(head.data)
            return self.res
    

    0x02 性能分析

    • 时间复杂度:O(n)
    • 空间复杂度:O(1)
  • 相关阅读:
    Python3 模块基础
    Python3 函数小练习
    Python3 函数进阶3
    Python3 函数进阶2
    Python3 函数进阶1
    Python3 函数实践之简易购物系统
    线程之间的通信
    volatile 关键字
    对象锁的同步与异步
    synchronized 关键字
  • 原文地址:https://www.cnblogs.com/LQ6H/p/12940578.html
Copyright © 2011-2022 走看看