標籤:棧 順序棧 資料結構 先進後出
棧是一種先進後出的資料結構.
棧的基本操作包括:入棧,出棧,初始化棧,清空棧,遍曆棧.
C代碼如下:
#include <stdio.h>#define MaxSize 20typedef int ElemType;typedef struct stack{ ElemType Data[MaxSize]; int top;}Stack;//初始化棧void InitStack(Stack *S){ S->top=-1;}//入棧void PushStackValue(Stack *S){ printf("Input the Value of stack member:\n(0-exit)\n"); int value; printf("Please input the 1st value of stack:\n"); scanf("%d",&value); S->Data[++S->top]=value; while(value) { S->top++; printf("Please input the %dst value of stack:\n",S->top+1); scanf("%d",&value); S->Data[S->top]=value; }}//出棧void PopStackValue(Stack *S){ if(S->top>=0) { printf("the stack %dst value pop out: %d\n",S->top+1,S->Data[--S->top]); } else { printf("The Stack is empty\n"); }}//判斷棧空void IsEmpty(Stack *S){ if(S->top==-1) { printf("The Stack is empty.\n"); } else { printf("The stack is not empty.\n"); }}//清空棧void ClearStack(Stack *S){ S->top=-1;}//遍曆棧void ScanStack(Stack *S){ int i; int len=S->top-1; int StackArray[len]; for(i=len;i>0;i--) { StackArray[i]=S->Data[i--]; } printf("The all stack member(from top to bottom) is:\n"); while(len>=0) { printf("%d ",S->Data[len--]); } printf("\n");}void main(){ Stack S; InitStack(&S); PushStackValue(&S); ScanStack(&S); IsEmpty(&S); PopStackValue(&S); PopStackValue(&S); PopStackValue(&S); PopStackValue(&S);}
運行結果如下:
轉載請註明作者:小劉