struct ListNode{ int m_nKey; ListNode m_pNext;}
思路:从头到尾遍历全体链表,将节点存入栈中,末了依次出栈。参考答案:
#include <iostream>#include <stack>using namespace std;struct ListNode{ int m_nKey; ListNode m_pNext;};void printListRev(ListNode pHead){stack<ListNode> nodes;ListNode pNode = pHead;while(pNode != NULL){ nodes.push(pNode); pNode = pNode->m_pNext;}while(!nodes.empty()){ pNode = nodes.top(); cout<<pNode->m_nKey<<'\t'; nodes.pop();}cout<<endl;}int main(){ListNode head = NULL;for(int i=10;i>0;i--){ ListNode p = new ListNode; p->m_nKey = i; p->m_pNext = head; head = p;}ListNode pNode = head;for(int i=0;i<10;i++){ cout<<pNode->m_nKey<<'\t'; pNode = pNode->m_pNext;}cout<<endl;printListRev(head);return 0;}
思路:要实现反过来输出链表,我们访问到一个节点的时候,先递归输出它后面的节点,再输出该节点本身,这样链表的输出就反过来了
参考代码:
#include <iostream>#include <stack>using namespace std;struct ListNode{ int m_nKey; ListNode m_pNext;};void printListRev(ListNode pHead){ if(pHead != NULL) { if(pHead->m_pNext != NULL) { printListRev(pHead->m_pNext); } cout<<pHead->m_nKey<<'\t'; }}int main(){ListNode head = NULL;for(int i=10;i>0;i--){ ListNode p = new ListNode; p->m_nKey = i; p->m_pNext = head; head = p;}ListNode pNode = head;for(int i=0;i<10;i++){ cout<<pNode->m_nKey<<'\t'; pNode = pNode->m_pNext;}cout<<endl;printListRev(head);cout<<endl;return 0;}