1.利用棧的數(shù)據(jù)結(jié)構(gòu)特點(diǎn)稽寒,將二進(jìn)制轉(zhuǎn)換為十進(jìn)制數(shù)
分析
由于棧具有先進(jìn)后出的特性侣背,我們輸入11001001的二進(jìn)制數(shù)卸留,出棧的順序就相反走越,將每個(gè)出棧的數(shù)帶入進(jìn)制轉(zhuǎn)換公式得到的結(jié)果就是轉(zhuǎn)換之后的十進(jìn)制數(shù)
完整代碼
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct {
ElemType * base;
ElemType * top;
int stackSize;
}sqStack;
/**
* 初始化
*/
void InitStack(sqStack * s){
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!s->base)
exit(0);
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
/**
* 進(jìn)棧
*/
void Push(sqStack * s, ElemType e){
if (s->top - s->base >= s->stackSize) { // 棧滿,擴(kuò)大空間
s->base = (ElemType *)realloc(s->base, (s->stackSize * STACKINCREMENT) * sizeof(ElemType));
if (!s->base)
exit(0);
s->top = s->base + s->stackSize; // 設(shè)置棧頂
s->stackSize = s->stackSize + STACKINCREMENT; // 設(shè)置棧的最大容量
}
*(s->top) = e;
s->top++;
}
/**
* 出棧
*/
void Pop(sqStack * s, ElemType *e){
if (s->top == s->base) // 棾苌空
return;
s->top--; // 棧頂指針減1
*e = *(s->top); // 將要?jiǎng)h除的棧頂元素賦值給e
// *e = *--(s->top);
}
/**
* 獲取棧的當(dāng)前容量
*/
int StackLen(sqStack s){
return (int)(s.top - s.base);
}
int main(int argc, const char * argv[]) {
ElemType e;
sqStack s;
int len,i,sum = 0;
// 初始化棧
InitStack(&s);
printf("請輸入二進(jìn)制數(shù)旨指,輸入#號(hào)表示結(jié)束!\n");
scanf("%c",&e);
while (e != '#') {
Push(&s, e);
scanf("%c", &e);
}
getchar(); // 把‘\n’從緩沖區(qū)去掉
len = StackLen(s);
printf("棧的當(dāng)前容量是:%d\n", len);
for (i = 0; i < len; i++) {
Pop(&s, &e);
sum = sum + (e-48) * pow(2, i); // 這里是ASCII碼喳整,所以要減去48
}
printf("轉(zhuǎn)化為十進(jìn)制數(shù)是:%d\n", sum);
return 0;
}