[编程题]从尾到头打印链表
题目描述:
输入一个链表,从尾到头打印链表每个节点的值
常规问题没什么费劲的,应该很容易想到利用栈的后进先出特性,将整个链表顺序压栈后弹出至动态数组中
C++
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* Head) {
stack<int> tmpstack;
vector<int> ans;
while(Head != NULL)
{
tmpstack.push(Head->val);
Head = Head->next;
}
while(!tmpstack.empty())
{
ans.push_back(tmpstack.top());
tmpstack.pop();
}
return ans;
}
};
2.python解法:先将链表中的值插入到新序列newlist中,之后再使用list的切片操作将序列逆置,则输出序列即可
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
newlist =[]
while listNode is not None:
newlist.append(listNode.val)
listNode = listNode.next
return newlist[::-1]