棧的基本操作有棧的初始化、插入數據、刪除數據以及遍歷棧。
棧的特點是先進后出,因此先插入的數據在遍歷的時候最后被輸出。刪除數據的時候,先刪除后插入的數據。
如下圖所示:
結構體定義代碼:(這是其中一種定義結構體的方法)
typedef struct Stack{ int *top; int *bottom; int Stack_size; }Stack;
相應的操作對應的代碼為:
//初始棧
int InitStack(Stack *stack){ stack->bottom=(int *)malloc(SIZE*sizeof(int)); stack->top=stack->bottom; stack->Stack_size=SIZE; return OK; }
//插入數據
int Push(Stack *stack,int data){ if(stack->top-stack->bottom>=stack->Stack_size){ printf("棧已滿,不能插入數據"); } *stack->top=data; stack->top++; return OK; }
//刪除數據
int Pop(Stack *stack){ if(stack->bottom==stack->top){ printf("棧為空,不能刪除數據"); } stack->top--; printf("%d\n",*stack->top); return OK; }
//遍歷棧
int print(Stack *stack) { while(stack->bottom!=stack->top){ stack->top--; printf("%d",*stack->top); } return OK; }
完整代碼為:
1 #define OK 1 2 #define ERROR 0 3 #define SIZE 100 4 typedef struct Stack{ 5 int *top; 6 int *bottom; 7 int Stack_size; 8 }Stack; 9 //初始棧 10 int InitStack(Stack *stack){ 11 stack->bottom=(int *)malloc(SIZE*sizeof(int)); 12 stack->top=stack->bottom; 13 stack->Stack_size=SIZE; 14 return OK; 15 } 16 //插入數據 17 int Push(Stack *stack,int data){ 18 if(stack->top-stack->bottom>=stack->Stack_size){ 19 printf("棧已滿,不能插入數據"); 20 } 21 *stack->top=data; 22 stack->top++; 23 return OK; 24 } 25 //刪除數據 26 int Pop(Stack *stack){ 27 if(stack->bottom==stack->top){ 28 printf("棧為空,不能刪除數據"); 29 } 30 stack->top--; 31 printf("%d\n",*stack->top); 32 return OK; 33 } 34 //遍歷棧 35 int print(Stack *stack) 36 { 37 while(stack->bottom!=stack->top){ 38 stack->top--; 39 printf("%d",*stack->top); 40 } 41 return OK; 42 } 43 int main() 44 { 45 Stack a; 46 InitStack(&a); 47 Push(&a,1); 48 Push(&a,2); 49 Push(&a,3); 50 printf("刪除的元素是:"); 51 Pop(&a); 52 printf("剩余的元素是:"); 53 print(&a); 54 return 0; 55 }
運行結果如圖所示: