剑指offer|从尾到头打印链表

来源:互联网 发布:淘宝买家钻号 编辑:程序博客网 时间:2024/06/16 18:32

题目描述
输入一个链表,从尾到头打印链表每个节点的值。
输入描述:

输入为链表的表头

输出描述:

输出为需要打印的“新链表”的表头

从头到尾遍历链表,并将节点打值存入一个栈中。
将栈中打节点值依次打印出来。

#include<iostream>#include<vector>#include<stack>using namespace std;struct ListNode {        int val;        struct ListNode *next;        ListNode(int x) :              val(x), next(NULL) {        } };vector<int> printListFromTailToHead(struct ListNode* head) {    vector<int> result;        if(head == nullptr)        return result;    stack<int> nodes;    ListNode* pNode=head;    while(pNode != nullptr)    {        nodes.push(pNode->val);        pNode=pNode->next;    }    while(!nodes.empty())    {        result.push_back(nodes.top());        nodes.pop();    }    return result;}int main(){    ListNode* pt=new ListNode(1);    pt->next=nullptr;    ListNode* ptemp=new ListNode(2);    ptemp->next=nullptr;    pt->next=ptemp;    vector<int> result;    result=printListFromTailToHead(pt);    for(auto c:result)        cout<<c<<" ";    cout<<endl;    return 0;}
0 0