堆栈存储及运算

    技术2023-03-29  39

    实验目的:

    1)了解堆栈相关概念;

    2)理解堆栈运算过程和结构定义;

    3)掌握算法转换为程序的过程中的变化。

    3、实验内容及要求:

    1)完成若干数据元素的进栈、出栈等运算;

    2)给出程序及堆栈运算过程的结果。

     

    /*堆栈的连是存储及操作 *2010.4.23 */ #include<iostream.h> #include<string.h> #define Student EType enum { OK ,ERROR }; typedef struct { int number; // char name[20]; }Student; //class of Student typedef struct StackNode { EType data; StackNode *link; }StackNode; //数据元素 typedef struct { StackNode *top; }ChainStack; //表头 void Creat(ChainStack *S) { S=new ChainStack; S->top=NULL; }// creat ChianStack int IsEmpty(ChainStack *S)//注意书上写的有问题!!! { if(!S->top) return 1; return 0; }//判断是否为空空时返回1非空返回0 int GetTop(ChainStack *S,EType *x) { if(IsEmpty (S)) return ERROR; StackNode *p=S->top; x->number=p->data.number; // cout<<x->number<<endl; return OK; }//返回栈顶值 int Push(ChainStack *S,EType *x) { StackNode *p=new StackNode ; p->data.number=x->number; p->link=S->top; S->top=p; return OK; }//push int Pop(ChainStack *S,EType *x) { if(IsEmpty(S)) return ERROR; StackNode *p=S->top; // x->number=S->top->data.number; x->number=p->data.number; S->top=p->link; delete p; return OK; }//pop int ShowWholeStack(ChainStack *S) { if(IsEmpty(S)) //????????????? { cout<<"The Stack is Empty!/n"; return ERROR; } /* ChainStack *current; current->top=S->top; while(current->top) { cout<<current->top->data.number<<" << "; } */ return OK; } int Add (ChainStack *S,int n) { StackNode *q=new StackNode; EType *x=new EType; x->number=n; q->data.number=x->number; Push(S,x); return OK; } void main() { cout<<"This is a simple of Stack!/n"; cout<<endl; ChainStack S; Creat(&S); cout<<"Now the Stack is following:/n"; ShowWholeStack(&S); cout<<endl; cout<<"Test of Push!/n"; cout<<"How Many Nodes do you want to add?/n"; int n; cin>>n; int temp; for (int i=1;i<=n;i++) { cout<<"Please Input a New Number"<<"("<<i<<")"<<"!/n"; cin>>temp; Add (&S,temp); } EType temp_EType; cout<<"Now the Stack is following:/n"; ShowWholeStack(&S); cout<<endl; cout<<"Now the Test of GetTop!/n"; GetTop(&S,&temp_EType); cout<<temp_EType.number<<endl; cout<<endl; cout<<"Now the Test of Pop!/n"; Pop(&S,&temp_EType); cout<<temp_EType.number<<endl; cout<<"Now the Top is Fllowing!/n"; cout<<S.top->data.number<<endl; }  

    最新回复(0)