题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
代码如下
/**
* 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> arr;
ListNode* p = head;
while(p != NULL)
{
arr.push(p->val);
p=p->next;
}
int len=arr.size();
for(int i=0;i<len;i++)
{
result.push_back(arr.top());
arr.pop();
}
return result;
}
};
本文介绍了一种使用栈实现链表逆序输出的方法。通过遍历链表将节点值压入栈中,再依次弹出栈顶元素,实现从尾到头的顺序输出。这种方法简洁高效,易于理解和实现。
202

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



