栈是一种先进后出的数据结构.栈的基本操作包括:入栈,出栈,初始化栈,清空栈,遍历栈.
C代码如下:
1 #include <stdio.h> 2 3 #define MaxSize 20 4 typedef int ElemType; 5 6 7 typedef struct stack 8 { 9 ElemType Data[MaxSize]; 10 int top; 11 }Stack; 12 13 //初始化栈 14 void InitStack(Stack *S) 15 { 16 S->top=-1; 17 } 18 19 //入栈 20 void PushStackValue(Stack *S) 21 { 22 printf("Input the Value of stack member: (0-exit) "); 23 int value; 24 printf("Please input the 1st value of stack: "); 25 scanf("%d",&value); 26 S->Data[++S->top]=value; 27 while(value) 28 { 29 S->top++; 30 printf("Please input the %dst value of stack: ",S->top+1); 31 scanf("%d",&value); 32 S->Data[S->top]=value; 33 } 34 } 35 36 //出栈 37 void PopStackValue(Stack *S) 38 { 39 if(S->top>=0) 40 { 41 printf("the stack %dst value pop out: %d ",S->top+1,S->Data[--S->top]); 42 } 43 else 44 { 45 printf("The Stack is empty "); 46 } 47 } 48 49 //判断栈空 50 void IsEmpty(Stack *S) 51 { 52 if(S->top==-1) 53 { 54 printf("The Stack is empty. "); 55 } 56 else 57 { 58 printf("The stack is not empty. "); 59 } 60 } 61 62 63 //清空栈 64 void ClearStack(Stack *S) 65 { 66 S->top=-1; 67 } 68 69 //遍历栈 70 void ScanStack(Stack *S) 71 { 72 int i; 73 int len=S->top-1; 74 int StackArray[len]; 75 for(i=len;i>0;i--) 76 { 77 StackArray[i]=S->Data[i--]; 78 } 79 printf("The all stack member(from top to bottom) is: "); 80 while(len>=0) 81 { 82 printf("%d ",S->Data[len--]); 83 } 84 printf(" "); 85 } 86 87 void main() 88 { 89 Stack S; 90 91 InitStack(&S); 92 PushStackValue(&S); 93 ScanStack(&S); 94 IsEmpty(&S); 95 PopStackValue(&S); 96 PopStackValue(&S); 97 PopStackValue(&S); 98 PopStackValue(&S); 99 }
运行结果如下: