1. 程式人生 > >棧的應用之進位制轉換

棧的應用之進位制轉換

舉一個十進位制轉成八進位制的例子

#include<stdio.h>
#include<stdlib.h>

typedef struct
{
	int *base;
	int *top;
	int stacksize;
}SqStack;

void Init(SqStack *S)
{
	S->stacksize = 100; 
	S->base=(int *)malloc(S->stacksize*sizeof(SqStack));
	S->top = S->base;
} 

int GetTop(SqStack S,int *e)
//獲取棧頂元素 
{
	if(S.top == S.base) return -1;  //棧空,函式執行失敗 
	*e = *(S.top-1);
	return 1;
}

int Push(SqStack *S,int x)
//向棧頂插入元素 
{
	if(S->top-S->base >= S->stacksize)  return -1;  //棧滿,函式執行失敗 
	 
	*S->top = x;
	S->top++;
	return 1; 
}

int Pop(SqStack *S,int *e)    
//彈出棧頂元素 
{
	if(S->top == S->base)  return -1;     //棧空 ,函式執行失敗 
	S->top--;
	*e = *S->top;
	return 1;
}

void conversion()
{
	SqStack S;
	int n,*e;
	printf("please put n:\n");
	scanf("%d",&n);
	Init(&S);
	while(n)
	{
		Push(&S,n%8);
		n = n/8;
	}
	while(S.top!=S.base)
	{
		Pop(&S,e);
		printf("%d",*e);
	}
}

int main()
{
	conversion();
	return 0;
}