#include <iostream> #include <cstdio> #include <stdlib.h> #include <stack> using namespace std; struct list { int data; list *next; }list1; list *initlist(int num) {//定义一个新节点 list *node=(list*)malloc(sizeof(list)); node->data=num; node->next=NULL; return node; } void pushback(list **pplist,int num) { if(*pplist==NULL) *pplist=initlist(num); else if((*pplist)->next==NULL) (*pplist)->next=initlist(num); else { list *tail=*pplist; while(tail->next) { tail=tail->next;//通过依次指向找到next为空的尾结点 } tail->next=initlist(num);//在最后添加一个结点 } } stack<int> s; int main(int argc, const char * argv[]) { list *l=NULL; int t; while(cin>>t) { pushback(&l, t); } while(l!=NULL) { t=l->data; s.push(t); l=l->next; } cout<<"NULL<-"; while(!s.empty()) { cout<<s.top()<<"<-"; s.pop(); } return 0; }
使用stack存储。