解题思路:
第一种方法:逆置单链表,然后输出;
第二种方法:利用栈的特性(先进后出),从头部入栈,然后出栈即可;
下面着重实现第二种方法。
代码实现
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution
{
public:
vector<int> printListFromTailToHead(ListNode* head)
{
stack<ListNode*> nodes;
ListNode* p = head;
while(p != NULL)
{
nodes.push(p);
p = p->next;
}
vector<int> result;
while(!nodes.empty())
{
p = nodes.top();
result.push_back(p->val);
nodes.pop();
}
return result;
}
};