输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# 先把元素全部输入到栈,利用栈的先进后出的特性,获得结果
stark = []
lyst = []
probe = listNode
while probe:
stark.append(probe.val)
probe = probe.next
while stark:
lyst.append(stark.pop())
return lyst
Python中取巧的做法,但分析其复杂度就会发现,完全不如上面那种解法:
def printListFromTailToHead(self, listNode):
lyst = []
probe = listNode
while probe:
lyst.insert(0, probe.val)
probe = probe.next
return lyst