题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路
利用栈这样的数据结构,可以将原来的顺序进行改变
做题可能出现的问题
1、python版本一般不会出现什么问题,稍微注意一下,倒序输出的表达方式。
2、c++中需要灵活使用自带的一些函数,如nodes.empty(),nodes.top(),nodes.pop()
vector用的是push_back, stack用的是push,具体参考下面的链接,c++中push方法和push_back方法
python
# -*- 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 not listNode:
return []
stack = []
res = []
p = listNode
while p:
stack.append(p.val)
p = p.next
for i in range(len(stack)-1,-1,-1):
res.append(stack[i])
return res
C++
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
stack<int> nodes;
struct ListNode* pNode = head;
while(pNode!=NULL)
{
nodes.push(pNode->val);
pNode = pNode->next;
}
while(!nodes.empty())
{
//pNode = nodes.top();
result.push_back(nodes.top());
nodes.pop();
}
return result;
}
};
C++版本二(使用reverse函数类似python)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> result;//用数组存储链表所有节点的值
struct ListNode* pNode = head;
while(pNode!=NULL)
{
result.push_back(pNode->val);
pNode = pNode->next;
}
reverse(result.begin(),result.end());//c++ ,翻转函数,对数组实现翻转
return result;
}
};
网友评论