剑指offer 05 从尾到头打印链表

来源:互联网 发布:数学画图软件 编辑:程序博客网 时间:2024/06/17 16:52

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

思路:

用堆栈,存储链表的值。


# -*- coding:utf-8 -*-# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass stack:    def __init__(self):        self.index = 0        self.content = []    def push(self, x):        self.index += 1        if len(self.content) < self.index:            self.content.append(x)        else:            self.content[self.index - 1] = x    def pop(self):        if self.index > 0:            self.index -= 1            return self.content[self.index]    def empty(self):        if self.index == 0:            return 1        return 0    class Solution:    # 返回从尾部到头部的列表值序列,例如[1,2,3]    def printListFromTailToHead(self, listNode):        # write code here        res_list = []        s = stack()        while listNode:            s.push(listNode.val)            listNode = listNode.next        while s.empty() is not 1:            res_list.append(s.pop())        return res_list