首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

两种方法兑现从尾到头打印链表-栈和递归

2013-09-09 
两种方法实现从尾到头打印链表--栈和递归#include iostream#include stackusing namespace stdstruct

两种方法实现从尾到头打印链表--栈和递归

#include <iostream>#include <stack>using namespace std;struct Node{int num;Node* pNext;};Node* AddToList(Node* p,int num){Node* pHead=NULL;Node* ptmp=(Node*)malloc(sizeof(Node));ptmp->num=num;ptmp->pNext=NULL;if(p==NULL)pHead=ptmp;else{pHead=p;while(p->pNext!=NULL)p=p->pNext;p->pNext=ptmp;}return pHead;}void Print(Node* p)//递归实现{if(p==NULL)return;if(p->pNext!=NULL){Print(p->pNext);cout<<p->num<<endl;}elsecout<<p->num<<endl;}void PrintByStack(Node* p)//栈实现{std::stack<Node*> nodes;Node* pTmp;while(p!=NULL){nodes.push(p);p=p->pNext;}while(!nodes.empty()){pTmp=nodes.top();cout<<pTmp->num<<endl;nodes.pop();}}void main(){Node* p=NULL;p=AddToList(p,1);p=AddToList(p,2);p=AddToList(p,3);p=AddToList(p,4);p=AddToList(p,5);p=AddToList(p,6);p=AddToList(p,7);p=AddToList(p,8);cout<<"//////////////////////"<<endl;Print(p);cout<<"//////////////////////"<<endl;PrintByStack(p);}

热点排行