从尾到头打印链表
输入一个链表,从尾到头打印链表每个节点的值。
/**
* 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;
vector<int> res;
ListNode* p=head;
while(p!=NULL)
{
nodes.push(p);
p=p->next;
}
while(!nodes.empty())
{
p=nodes.top();
res.push_back(p->val);
//printf("%d\t",p->val);
nodes.pop();
}
return res;
}
};
或者
/**
* 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> node;
ListNode *p=head;
while(p)
{
node.push(p->val);
p=p->next;
}
while (!node.empty())
{
int q;
q=node.top();
result.push_back(q);
node.pop();
}
return result;
}
};