採用順序儲存實現棧的初始化、入棧、出棧操作。/驗證實驗/
#include<stdlib.h>
#define maxsize 100
typedef struct SqStack
{
int data[maxsize];
int top;
}SqStack;
void SqStackEmpty(SqStack *st)//判斷棧是否為空
{
st->top==-1?printf("棧仍為空,操作可能有風險建議重新除錯程式\n"): printf("棧不為空,操作可正常進行\n");
}
void push(SqStack *st,int i)//進棧
{
if(st->top+i>=maxsize-1)
{ printf("overflow! 不能進棧!\n"); }
else
{ printf("請輸入你要進棧的%d個數據:\n",i);
for(int a=0;a<i;a++)
scanf("%d",&st->data[++st->top]); }
}
void pop(SqStack *st,int j)//出棧
{
if(st->top==-1)
{ printf("空棧怎能出棧!\n"); }
else if(st->top-j<-1)
{ printf("要求出棧的元素過多,已超出棧的儲存量");}
else
{
printf("出棧的資料是:\n");
for(int a=0;a<j;a++)
printf("%d ",st->data[st->top--]);
}
printf("\n");
}
void printStack(SqStack *st)//列印棧內當前所有的棧元素
{
while(st->top !=-1)
{
printf("棧元素:%d\n",st->data[st->top--]);
}
}
void main(){
int i,j,a;
SqStack st={{1,2,3,4},3}; //存入四個資料,以及top的位置即4-1=3,top來指示當前棧頂元素的位置
SqStackEmpty(&st);
while(1)
{printf("輸入1進棧、2出棧、3列印棧\n");
scanf("%d",&a);
if(a==1)
{printf("輸入你要進棧資料的個數:\n");
scanf("%d",&i);
push(&st,i);
continue;}
if(a==2)
{printf("輸入你要出棧資料的個數:\n");
scanf("%d",&j);
pop(&st,j);
continue;}
if(a==3)
{printf("棧內資料:\n");
printStack(&st);
continue;}
else
{printf("輸入有誤,請重新輸入!\n");
continue;}}
}