[剑指offer][面试题5]从尾到头打印链表

来源:互联网 发布:人工智能机器人电影 编辑:程序博客网 时间:2024/06/09 22:09
#include <iostream>#include <stack>using namespace std;struct Node{int   m_Data;Node *m_pNext;};void printReverseList_Recursive(Node *pHead){if (pHead){printReverseList_Recursive(pHead->m_pNext);cout<<pHead->m_Data<<"->";}}void printReverseList_Iterative(Node *pHead){if (pHead==NULL){return;}stack<int> s;while (pHead){s.push(pHead->m_Data);pHead = pHead->m_pNext;}while (!s.empty()){cout<<s.top()<<"->";s.pop();}cout<<"NULL"<<endl;}int main(){Node node5 = {5, NULL};Node node4 = {4, &node5};Node node3 = {3, &node4};Node node2 = {2, &node3};Node node1 = {1, &node2};Node node0 = {0, &node1};Node *pHead = &node0;Node *pHead1 = &node0;//print listcout<<"Linked List: "<<endl;while (pHead1){cout<<pHead1->m_Data<<"->";pHead1 = pHead1->m_pNext;}cout<<"NULL"<<endl;//print list from tail to headcout<<"Reverse Order (Recursive): "<<endl;printReverseList_Recursive(pHead);cout<<"NULL"<<endl;//print list from tail to headcout<<"Reverse Order (Iterative): "<<endl;printReverseList_Iterative(pHead);}

原创粉丝点击