棧標頭檔
/* * ADTStack.h * * Created on: 2013-5-26 * Author: inner */#ifndef ADTSTACK_H_#define ADTSTACK_H_#define STACK_INT_SIZE 100#define STACKINCREMENT 10typedef int sElemType;typedef struct{sElemType *top;sElemType *base;int stacksize;}SqStack;//初始化 void InitStack(SqStack *stack); //銷毀棧 void DestroyStack(SqStack *stack); //入棧 void Push(SqStack *stack,sElemType elem); //出棧 int pop(SqStack *stack); //棧頂元素 int getTop(SqStack *stack); //判斷棧是否為空白 int IsEmpty(SqStack *stack);#endif /* ADTSTACK_H_ */
棧源檔案
/* * StackMake.c * * Created on: 2013-5-26 * Author: inner */#include <stdio.h>#include <stdlib.h>#include "ADTStack.h" void InitStack(SqStack *stack){//分配記憶體空間stack->top = (sElemType*)malloc(STACK_INT_SIZE*sizeof(sElemType));if(!stack->top)exit(1);stack->base = stack->top;stack->stacksize = STACK_INT_SIZE;printf("初始化成功\n"); } void Push(SqStack *stack,sElemType elem){ if(stack->top-stack->base>=stack->stacksize){ stack->base =(sElemType*)realloc(stack->base,(STACKINCREMENT+STACK_INT_SIZE)*sizeof(sElemType)); } *stack->top = elem; ++stack->top; printf("入棧為%d\n",elem); printf("棧大小%d\n",stack->top-stack->base); } int pop(SqStack *stack){ //檢查棧是否為空白 if(stack->top-stack->base == 0){ printf("棧為空白"); exit(0); } int kk; kk = *--stack->top; printf("出站為%d\n",kk); printf("棧大小%d\n",stack->top-stack->base); return kk; } int getTop(SqStack *stack){ if(IsEmpty(stack)) exit(0); int kk = *(--stack->top); printf("棧頂元素為:%d",kk); return kk; } int IsEmpty(SqStack *stack){ if(stack->top-stack->base == 0){ printf("棧已經為空白"); return 1; } return 0; }
棧的進位轉換執行檔案
#include <stdio.h>#include <stdlib.h>#include "ADTStack.h"void conversion(int,int);int main(void) {int a, b;printf("輸入十進位數\n");scanf("%d",&a);printf("輸入要轉換進位\n");scanf("%d",&b);conversion(a,b);return EXIT_SUCCESS;}void conversion(int a,int b){SqStack S;InitStack(&S);while(a){Push(&S,a%b);a=a/b;}while(!IsEmpty(&S)){printf("%d",pop(&S));}}
棧的進位執行個體效果
輸入十進位數
88888
輸入要轉換進位
7
初始化成功
入棧為2
棧大小1
入棧為0
棧大小2
入棧為1
棧大小3
入棧為0
棧大小4
入棧為2
棧大小5
入棧為5
棧大小6
520102棧已經為空白
棧的介面測試
int main(void) { SqStack stack; InitStack(&stack); Push(&stack,688); Push(&stack,66555); pop(&stack); getTop(&stack); return EXIT_SUCCESS;}
棧的介面的執行個體效果
初始化成功
入棧為688
棧大小1
入棧為66555
棧大小2
出站為66555
棧大小1
棧頂元素為:688
簡單的棧就到這裡了。。。。