考研數據結構-棧
1.結構
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define INITSIZE 20
#define INSERTMENT 10
typedef char ElemType;
typedef struct{
ElemType *base;
ElemType *top;
int stacksize;
}sqStack;
2.初始化
void initStack(sqStack *s){
s->base=(ElemType *)malloc(INITSIZE*sizeof(ElemType));
if(!s->base) exit(0);
s->top=s->base;
s->stacksize=INITSIZE;
}
3.入棧
void push(sqStack *s,ElemType e){
if(s->top - s->base >= s->stacksize){
s->base=(ElemType *)realloc(s->base,(s->stacksize+INSERTMENT)*sizeof(ElemType));
if(!s->base) exit(0);
s->top=s->base+s->stacksize;
s->stacksize=s->stacksize+INSERTMENT;
}
*(s->top)=e;
s->top++;
}
4.出棧
void pop(sqStack *s,ElemType *e){
if(s->top==s->base) return;
*e=*--(s->top);
}
5.獲取棧長
int StackLen(sqStack s){
return (s.top - s.base);
}
6.銷燬棧
void destroyStack(sqStack *s){
free(s->base);
s->base = s->top = NULL;
s->stacksize=0;
}
7.測試代碼
int main() {
ElemType c;
sqStack s;
int len,i;
int sum=0;
printf("請輸入二進制數字,#結尾:");
initStack(&s);
scanf("%c",&c);
while(c!='#'){
push(&s,c);
scanf("%c",&c);
}
getchar();
len = StackLen(s);
for(i=0;i<len;i++){
pop(&s, &c);
printf("c:%c\n",c);
sum=sum+(c-48)*pow(2,i);
}
printf("十進制爲:%d\n",sum);
destroyStack(&s);
}