链栈
能理解这个图就OK了。
#include <iostream> using namespace std; typedef int DataType; struct Node{ DataType data; struct Node *link ; }; typedef Node *PNode; struct LinkStack{ PNode top; }; typedef LinkStack *PLinkStack; PLinkStack createEmptyStack() { PLinkStack plstack = (PLinkStack) malloc (sizeof(struct LinkStack)); if(plstack != NULL) plstack ->top = NULL; else cout<<"Out of spaces\n"; return plstack; } int isEmpty(PLinkStack plstack) { return plstack ->top ==NULL; } void push(PLinkStack plstack,DataType x) { PNode p = (PNode) malloc (sizeof (struct Node)); if(p!= NULL) { p ->data = x; p ->link = plstack -> top; //新元素的指针域指向栈顶元素。 plstack -> top = p; //新加入的元素作为栈顶。 } else cout<<"Out of space\n"; } void pop(PLinkStack plstack) { PNode p = (PNode) malloc (sizeof(struct Node)); if (p!= NULL) { p = plstack -> top; plstack ->top = plstack -> top -> link; //栈顶元素的下一个元素作为新的栈顶。 free(p); } else cout<<"Empty stack\n"; } DataType printTop(PLinkStack plstack) { return plstack ->top ->data; } int main() { int n; cin>>n; int t = n; int item; PLinkStack plstack = createEmptyStack(); while(n) { cin>>item; push(plstack,item); n--; } while(t) { cout<<printTop(plstack)<<" "; pop(plstack); t--; } system("pause"); return 0; }