剑指offer从头到尾打印链表

来源:互联网 发布:ubuntu开启root账户 编辑:程序博客网 时间:2024/06/07 13:13

输入一个链表,从尾到头打印链表每个节点的值。


1从尾到头,即先进后出,可以用栈实现

2先翻转链表,然后依次从头到尾输出

3递归实现

4利用反向迭代器输出

#include<iostream>#include<cstdio>#include<cstdlib>#include<stack>#include<vector>using namespace std;typedef struct ListNode{int value;ListNode *next;}ListNode;void printList(ListNode* pHead)//递归{    ListNode* pNode=pHead;    if(pNode==NULL)        return ;    printList(pNode->next);    cout<<pNode->value<<endl;    return ;}int main(){    ListNode* a=(ListNode*)malloc(sizeof(ListNode));    a->value=10;    a->next=NULL;    ListNode* a1=a;    for(int i=10;i<15;i++)    {        ListNode* b=(ListNode*)malloc(sizeof(ListNode));        b->value=i*2;        b->next=NULL;        a1->next=b;        a1=b;    }    a1=a;    while(a1!=NULL)    {        cout<<a1->value<<" ";        a1=a1->next;    }    cout<<endl;    printList(a);    return 0;}//栈的实现void printList(ListNode* pHead){    ListNode* pHead=pHead;    stack<ListNode*>s;    if(pNode==NULL)        return;    while(p!=NULL)    {        s.push(pNode);        pNode=pNode->next;    }    while(!s.empty())    {        pNode=s.top();        cout<<pNode->value<<" ";        s.pop();    }    cout<<endl;    return ;}//反向迭代器vector<int> printfList(ListNode* head){    vector<int> v;    ListNode *p=head;    while(p!=nullptr)    {        v,push_back(p->val);        p=p->next;    }    return vector<int>(v.rbegin(),v.rend());}


阅读全文
0 0
原创粉丝点击