能理解這個圖就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; }