#include <stdio.h>
#include <stdlib.h>
#define DataType int
#define STACK_SIZE 100
typedef struct stack
{
DataType *base;
DataType *top;
int stacksize;
}SeqStack;
/*构造一个空栈 */
void Initial(SeqStack *s)
{
s->base = (DataType*)malloc(sizeof(DataType)*STACK_SIZE); //建立一个指针数组
if(!s->base) exit(1);
s->top = s->base;
s->stacksize = STACK_SIZE;
}
/*判栈空*/
int isEmpty(SeqStack *s)
{
return s->top == s->base;
}
/*判栈满*/
int isFull(SeqStack *s)
{
return s->top - s->base == STACK_SIZE-1;
}
/*进栈*/
void Push(SeqStack *S, DataType x)
{
if(isFull(S))
{
printf("the stack is full!"); //栈上溢;
exit(1);
}
*S->top++ = x; //这里的*表示的是取S中top指针数组的元素
}
/*出栈*/
DataType Pop(SeqStack*S)
{
if(isEmpty(S))
{
printf("the stack is empty!"); //栈下溢;
exit(1);
}
return *(--S->top);
}
/*取栈顶元素*/
DataType Top(SeqStack*S)
{
if(isEmpty(S))
{
printf("the stack is empty!"); //下溢,退出运行;
exit(1);
}
return *(S->top-1);
}
void feelthebase(int N,int B) //N is a decimal non-negative number ; B is the hexadecimal number;
{
SeqStack *S = (SeqStack*)malloc(sizeof(SeqStack));
int x, i=0;
Initial(S);
while(N)
{
Push(S,N%B);
N = N/B;
}
while(!isEmpty(S))
{
x= Pop(S);
printf("%d",x);
i++;
if(i % 4 == 0) printf(" ");
}
}
//对于结构体中的指针数组,*表示取其值,而*++s 和*s++ 其含义是不同的;
int main()
{
int N,B;
printf("please input the number you want to conversion:\n");
scanf("%d",&N);
printf("please input the hexadecimal number:\n");
scanf("%d",&B);
feelthebase(N,B);
return 0;
}
stack实现进制转换--hexadecimal
最新推荐文章于 2024-07-20 23:55:03 发布