将一个链表从后到前进行打印

来源:互联网 发布:golang.org上不去 编辑:程序博客网 时间:2024/04/30 10:40

题目是:有一个链表,需要从后到前将其节点内的值进行打印一份,我们知道单链表的访问是从头结点开始,一个一个向后访问,如果想要首先输出尾节点的话,就要将链表访问过的这些值存起来,然后最后再倒序输出即可,此时,应用栈是一个非常不错的想法。

#include <iostream>#include <stack>using namespace std;struct listNode{    int value;    listNode *next;};int printList(listNode *head stack<int> &st){    while(head != NULL)    {           st.push(head->m_nValue);        head = head->next;    }       while( !st.empty())    {           cout<<st.pop()<<endl;    }   }

将访问过的节点放入栈内,然后访问完后,从栈中弹出即可。

0 0