标签:
栈的一些操作
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; typedef struct Node { int data; struct Node * next; }Node,*PNode; typedef struct Stack { PNode top; }Stack,*PStack; //函数声明 void showlist(); void selection(PStack S); void InitStack(PStack S); void PushStack(PStack S); void PopStack(PStack S); void PrintStack(PStack S); bool EmptyStack(PStack S); void GetTopElem(PStack S); void GetCount(PStack S); int main() { Stack s; InitStack(&s); selection(&s); system("pause"); return 0; } void showlist() { system("color 3e"); cout<<"**********************************"<<endl;; cout<<"************1.入栈****************"<<endl; cout<<"************2.出栈****************"<<endl; cout<<"************3.打印栈元素**********"<<endl; cout<<"************4.栈顶元素元素********"<<endl; cout<<"************5.栈元素个数**********"<<endl; cout<<"************6.退出****************"<<endl; cout<<"**********************************"<<endl; cout<<"**********************************"<<endl; } void selection(PStack s) { int opt; showlist(); while(1) { cout<<"请选择你的操作:"; cin>>opt; switch(opt) { case 1: PushStack(s); break; case 2: PopStack(s); break; case 3: PrintStack(s); break; case 4: GetTopElem(s); break; case 5: GetCount(s); break; case 6: exit(-1); } } } //初始化 void InitStack(PStack S) { S->top=(PNode)malloc(sizeof(Node)); if(!S->top) cout<<"初始化失败!"<<endl; else { S->top=NULL; cout<<"初始化栈成功!"<<endl; } } //入栈 void PushStack(PStack S) { int n; int x; cout<<"请输入要入栈的个数:"; cin>>n; for(int i=1;i<=n;i++) { cout<<"请输入第"<<i<<"个元素的值:"; cin>>x; PNode p; p=(PNode)malloc(sizeof(Node));//申请节点 p->data=x; p->next=S->top; S->top=p; } } //打印栈元素 void PrintStack(PStack S) { PNode p; p=S->top; //指向栈顶元素 cout<<"遍历栈元素的结果是:"; if(EmptyStack(S)) cout<<"栈空,没有元素要打印!!"<<endl; else { while(p!=NULL) { cout<<p->data<<" "; p=p->next; } } cout<<endl; } //出栈 void PopStack(PStack S) { PNode p; p=S->top; if(EmptyStack(S)) { cout<<"栈空!"<<endl; } else { cout<<"出栈的元素是:"<<p->data<<endl; S->top=p->next; free(p); } } //判空栈 bool EmptyStack(PStack S) { if(S->top==NULL) return true; else return false; } void GetTopElem(PStack S) { if(EmptyStack(S)) cout<<"栈为空,没有栈顶元素!"<<endl; else { cout<<"栈顶元素是:"<<S->top->data<<endl; } } void GetCount(PStack S) { PNode p; p=S->top; //指向栈顶元素 int count=0; cout<<"遍历栈元素的结果是:"; if(EmptyStack(S)) cout<<0<<endl; else { while(p!=NULL) { count++; p=p->next; } } cout<<count; cout<<endl; }
运行结果:
标签:
原文地址:http://my.oschina.net/lvguidong/blog/522038