棧(stack)又名堆疊,它是一種運算受限的線性表。其限制是僅允許在表的一端進行插入和刪除運算。這一端被稱為棧頂,相對地,把另一端稱為棧底。向一個棧插入新元素又稱作進棧、入棧或壓棧,它是把新元素放到棧頂元素的上面,使之成為新的棧頂元素;從一個棧刪除元素又稱作出棧或退棧,它是把棧頂元素刪除掉,使其相鄰的元素成為新的棧頂元素。
基本介紹
基本概念
基本算法
實現
pascal
C++代碼
#include<iostream>classSqStack{private:enum{MaxSize=100};intdata[MaxSize];inttop;public:SqStack();~SqStack();boolisEmpty();voidpushInt(intx);intpopInt();intgetTop();voiddisplay();};SqStack::SqStack(){top=-1;}SqStack::~SqStack(){}boolSqStack::isEmpty()//判斷棧為空{return(top==-1);}voidSqStack::pushInt(intx)//元素進棧{if(top==MaxSize-1){std::cout<<"棧上溢出!"<<std::endl;}else{++top;data[top]=x;}}intSqStack::popInt()//退棧{inttmp=0;if(top==-1){std::cout<<"棧已空!"<<std::endl;}else{tmp=data[top--];}returntmp;}intSqStack::getTop()//獲得棧頂元素{inttmp=0;if(top==-1){std::cout<<"棧空!"<<std::endl;}else{tmp=data[top];}returntmp;}voidSqStack::display()//列印棧里元素{std::cout<<"棧中元素:"<<std::endl;for(intindex=top;index>=0;--index){std::cout<<data[index]<<std::endl;}}intmain(){SqStackst;std::cout<<"棧空:"<<st.isEmpty()<<std::endl;for(inti=1;i<10;i++){st.pushInt(i);}st.display();std::cout<<"退一次棧"<<std::endl;st.popInt();std::cout<<"棧頂元素:"<<st.getTop()<<std::endl;st.popInt();st.display();return0;}
C代碼
#include<stdio.h>#include<malloc.h>#defineDataTypeint#defineMAXSIZE1024typedefstruct{DataTypedata[MAXSIZE];inttop;}SeqStack;SeqStack*Init_SeqStack()//棧初始化{SeqStack*s;s=(SeqStack*)malloc(sizeof(SeqStack));if(!s){printf("空間不足\n");returnNULL;}else{s->top=-1;returns;}}intEmpty_SeqStack(SeqStack*s)//判棧空{if(s->top==-1)return1;elsereturn0;}intPush_SeqStack(SeqStack*s,DataTypex)//入棧{if(s->top==MAXSIZE-1)return0;//棧滿不能入棧else{s->top++;s->data[s->top]=x;return1;}}intPop_SeqStack(SeqStack*s,DataType*x)//出棧{if(Empty_SeqStack(s))return0;//棧空不能出棧else{*x=s->data[s->top];s->top--;return1;}//棧頂元素存入*x,返回}DataTypeTop_SeqStack(SeqStack*s)//取棧頂元素{if(Empty_SeqStack(s))return0;//棧空elsereturns->data[s->top];}intPrint_SeqStack(SeqStack*s){inti;printf("當前棧中的元素:\n");for(i=s->top;i>=0;i--)printf("%3d",s->data[i]);printf("\n");return0;}intmain(){SeqStack*L;intn,num,m;inti;L=Init_SeqStack();printf("初始化完成\n");printf("棧空:%d\n",Empty_SeqStack(L));printf("請輸入入棧元素個數:\n");scanf("%d",&n);printf("請輸入要入棧的%d個元素:\n",n);for(i=0;i<n;i++){scanf("%d",&num);Push_SeqStack(L,num);}Print_SeqStack(L);printf("棧頂元素:%d\n",Top_SeqStack(L));printf("請輸入要出棧的元素個數(不能超過%d個):\n",n);scanf("%d",&n);printf("依次出棧的%d個元素:\n",n);for(i=0;i<n;i++){Pop_SeqStack(L,&m);printf("%3d",m);}printf("\n");Print_SeqStack(L);printf("棧頂元素:%d\n",Top_SeqStack(L));return0;}