LinkStack:
//链式栈 #include<iostream> using namespace std; typedef int elemType; typedef struct StackNode { elemType data; StackNode *next; }*LinkList; struct LinkStack { LinkList top; int count; }; //初始化 void InitStack(LinkStack *S) { S->top = NULL; S->count = 0; } //判断是否为空 bool EmptyStack(LinkStack *S) { if(S->count==0) return true; else return false; } //进栈 void Push(LinkStack *S, elemType e) { LinkList p = new StackNode; p->data = e; p->next = S->top; S->top = p; S->count++; } //出栈 void Pop(LinkStack *S, elemType *e) { LinkList p = new StackNode; if(EmptyStack(S)) cout<<"出错,栈已为空."<<endl; *e = S->top->data; p = S->top; S->top = p->next; delete p; S->count--; } //获取栈顶元素 int GetTop(LinkStack *S) { if(S->count==0) cout<<"无法获取,栈为空."<<endl; elemType e; e = S->top->data; return e; } void TraStack(LinkStack *S) { if(S->count==0) cout<<"栈为空."<<endl; LinkList p = S->top; int i = 1; while(p!=NULL) { cout << i <<": "<< p->data<<endl; p = p->next; i++; } } //清空栈 bool ClearStack(LinkStack *S) { if(S->count==0) { cout<<"栈已为空,无需清空."<<endl; return false; } int num = S->count; while(num>=0) { LinkList p = new StackNode; p = S->top; if(num==0) { S->top = NULL; S->count = 0; } else { S->top = p->next; } delete p; num--; } return true; } int main() { LinkStack s; InitStack(&s); for(int i=1;i<7;i++) Push(&s,i); TraStack(&s); cout<<endl; elemType x = GetTop(&s); cout<<"栈顶元素为: "<< x <<endl; elemType i=0;; Pop(&s, &i); cout<<"删除栈顶元素后栈为:"<<endl; TraStack(&s); cout<<endl; ClearStack(&s); cout<<"清空栈..."<<endl; TraStack(&s); if(EmptyStack(&s)) cout <<"栈已经为空!"<<endl; cout<<endl; return 0; }