C語言實現順序棧的入棧、出棧、棧元素讀取操作
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define MaxSize 20 4 #define MaxNum 10 5 #define ElemType int 6 typedef struct SqStack 7 { //存儲結構定義 8 ElemType elem[MaxSize]; //棧元素的存儲空間 9 int top; //棧頂指針 10 }SqStack; //存儲結構類型名 11 12 void Init_SqStack(SqStack *s) 13 { 14 s->top = -1; 15 } 16 17 void Push(SqStack *s,ElemType x) 18 { 19 if (s->top < MaxSize - 1) 20 { 21 s->top = s->top + 1; 22 s->elem[s->top] = x; 23 } 24 else 25 printf("棧已滿,不能入棧!\n"); 26 } 27 28 int Pop(SqStack *s) 29 { 30 ElemType x; 31 if (s->top != -1) 32 { 33 x = s->elem[s->top]; 34 s->top = s->top-1; 35 return x; 36 } 37 else 38 { 39 printf("棧為空,不能出棧!\n"); 40 return 0; 41 } 42 } 43 44 int Get_Top(SqStack *s,ElemType x) 45 { 46 if (s->top != -1) 47 { 48 x = s->elem[s->top]; 49 } 50 else 51 { 52 printf("棧為空!\n"); 53 return 0; 54 } 55 } 56 57 int Get_Base(SqStack *s,ElemType x) 58 { 59 if (s->top != -1) 60 { 61 x = s->elem[0]; 62 } 63 else 64 { 65 printf("棧為空!\n"); 66 return 0; 67 } 68 } 69 70 void Display00_SqStack(SqStack *s) 71 { 72 int n; 73 if (s->top == -1) 74 printf("順序棧為空"); 75 else 76 { 77 for (n = 0; n <= s->top; n ++) 78 printf("%d ",s->elem[n]); 79 printf("\n"); 80 } 81 } 82 83 void Display01_SqStack(SqStack *s) 84 { 85 int m; 86 if (s->top == -1) 87 printf("順序棧為空!\n"); 88 else 89 { 90 for (m = s->top; m >= 0; m--) 91 printf("%d ",s->elem[m]); 92 printf("\n"); 93 } 94 } 95 96 int main() 97 { 98 SqStack s; 99 int x,y,cord,p; 100 ElemType a; 101 Init_SqStack(&s); 102 for (int t = 1; t <= MaxNum; t++) 103 { 104 Push(&s,t); 105 } 106 printf("初始化\n依次進棧元素為:\n"); 107 Display00_SqStack(&s); 108 printf("從棧頂到棧底元素為: \n"); 109 Display01_SqStack(&s); 110 do{ 111 printf("\n 主菜單 \n"); 112 printf(" 1 入棧 \n"); 113 printf(" 2 出棧 \n"); 114 printf(" 3 讀棧頂元素 \n"); 115 printf(" 4 讀棧底元素 \n"); 116 printf(" 5 結束程序 \n"); 117 printf("-----------------------------------------------------\n"); 118 printf("請輸入你選擇的菜單號<1,2,3,4>: "); 119 scanf("%d",&cord); 120 switch(cord) 121 { 122 case 1: 123 printf("請輸入入棧元素:"); 124 scanf("%d",&a); 125 Push(&s,a); 126 printf("由棧頂到棧底的元素為: \n"); 127 Display01_SqStack(&s); 128 break; 129 case 2: 130 x = Pop(&s); 131 printf("出棧元素為: %d\n",x); 132 printf("由棧頂到棧底的元素為: \n"); 133 Display01_SqStack(&s); 134 break; 135 case 3: 136 y = Get_Top(&s,x); 137 printf("棧頂元素為: %d\n",y); 138 printf("由棧頂到棧底的元素為: \n"); 139 Display01_SqStack(&s); 140 break; 141 case 4: 142 p = Get_Base(&s,x); 143 printf("棧底元素為: %d\n",p); 144 printf("由棧頂到棧底的元素為: \n"); 145 Display01_SqStack(&s); 146 break; 147 case 5: 148 exit(0); 149 break; 150 default: 151 printf("輸入有誤!"); 152 } 153 } 154 while(cord <= 4); 155 }
運行結果: