从头到尾打印链表
题目简单,算法上是使用一个栈就行了,先进后出。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
if listNode == None:
return []
stack = []
res = []
while listNode != None:
stack.append(listNode.val)
listNode = listNode.next
for i in range(len(stack))
res.append(stack.pop())
return res
本文介绍了一种使用栈实现从尾部到头部打印链表的方法。通过遍历链表将节点值压入栈中,再依次弹出,实现了链表元素的逆序输出。
5万+

被折叠的 条评论
为什么被折叠?



