链栈基本操作
2012-08-22 09:25
204 查看
链栈的操作:
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; struct node { int val; node *next; }; node *push(node *top,int x) { node *p = new node(); p->val = x; p->next = top; top = p; return top; } node *pop(node *top,int *x) { if(top == NULL) return NULL; node *q = top; *x = top->val; top = top->next; delete q; return top; } void print(node *top) { node *p = top; if(p == NULL) return; while(p != NULL) { printf("%d ",p->val); p = p->next; } cout<<endl; } int main() { int n,x; node *top = NULL; while(cin>>n) { while(n--) { cin>>x; top = push(top,x); } print(top); top = pop(top,&x); cout<<x<<endl; } return 0; }