class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
std::stack<int> nodes;
vector<int> outnodes;
ListNode *pNode = head;
while (head != NULL)
{
nodes.push(head->val);
head = head->next;
}
while (!nodes.empty())
{
outnodes.push_back(nodes.top());
nodes.pop();
}
return outnodes;
}
};
本文介绍了一种使用栈来逆序打印链表元素的方法。通过遍历链表并将每个节点的值压入栈中,再依次弹出栈顶元素,实现了从尾到头的打印效果。此方法适用于C++环境,利用了STL中的栈和向量容器。
615

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



