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)
posted @ 2019-11-07 11:51  LQ6H  阅读(87)  评论(0编辑  收藏  举报