小白的資料結構程式碼實戰(6)----共享棧
阿新 • • 發佈:2018-12-15
共享棧=棧1+棧2
棧1的棧底為共享棧的首,棧2的棧底為共享棧的尾
共享棧滿:S->top1+1==S->top2
//Author:張佳琪 #include <stdio.h> #include <stdlib.h> #define MAXSIZE 80 #define ERROR 0 #define OK 1 #define TRUE 1 #define FALSE 0 typedef int ElemType; typedef int Status; typedef struct { ElemType data[MAXSIZE]; int top1; int top2; }Stack; Status init(Stack *S) { S->top1=-1; S->top2=MAXSIZE; return OK; } Status push(Stack *S,ElemType e,int stacknumber) { if(S->top1+1==S->top2) return ERROR; if(stacknumber==1) { S->data[++S->top1]=e; } else if(stacknumber==2) { S->data[--S->top2]=e; } return OK; } Status pop(Stack *S,ElemType *e,int stacknumber) { if(stacknumber==1) { if(S->top1==-1) return ERROR; *e=S->data[S->top1--]; } else if(stacknumber==2) { if(S->top2==MAXSIZE) return ERROR; *e=S->data[S->top2++]; } return OK; } Status show(Stack *S,int stacknumber) { int i; if(stacknumber==1) { if(S->top1==-1) return ERROR; printf("棧1:"); for(i=0;i<=S->top1;i++) printf("%d ",S->data[i]); printf("\n=================\n"); } else if(stacknumber==2) { if(S->top2==MAXSIZE) return ERROR; printf("棧2:"); for(i=MAXSIZE-1;i>=S->top2;i--) printf("%d ",S->data[i]); printf("\n=================\n"); } return OK; } int main() { Stack S; ElemType x; int i; while(1) { printf("=====menu=====\n"); printf("1.初始化\n"); printf("2.入棧\n"); printf("3.出棧\n"); printf("4.輸出\n"); printf("輸入1-4:"); scanf("%d",&i); switch(i) { case 1: { if(init(&S)) printf("完成!\n"); else printf("失敗!\n"); break; } case 2: { printf("棧1還是棧2:"); scanf("%d",&i); printf("輸入資料:"); scanf("%d",&x); push(&S,x,i); break; } case 3: { printf("棧1還是棧2:"); scanf("%d",&i); pop(&S,&x,i); printf("%d\n",x); break; } case 4: { printf("棧1還是棧2:"); scanf("%d",&i); show(&S,i); break; } } } }