顺序栈的实现(数值转换为例)
include<stdio.h>
include<stdlib.h>
include<string.h>
include<malloc.h>
define STACK_INIT_SIZE 100
define STACKINCREASE 10
define ERROR 0
define OK 1
define OVERFLOW -1
//顺序栈的实现(栈的特点是后进先出)
typedef struct
{
int *base;
int *top;
int stacksize;//指申请空间的大小,不是指栈里面元素的数量
}SqStack;
//构造一个空栈
int InitStack(SqStack p)//里面的参数应该带个星号,但显示不出来
{
p->base = (int)malloc(sizeof(int) * STACK_INIT_SIZE);
if (!p->base) exit(OVERFLOW);
p->top = p->base;
p->stacksize = STACK_INIT_SIZE;
return OK;
}
//销毁栈
int DestoyStack(SqStack *p)
{
if (!p->base) return ERROR;
free(p->base);
p->base = NULL;
p->stacksize = 0;
return OK;
}
//清空栈
int ClearStack(SqStack *p)
{
if (!p->base) return ERROR;
p->top = p->base;
return OK;
}
//检查栈是否为空
int StackEmpty(SqStack p)
{
if (!p.base) return ERROR;
if (p.top == p.base) return OK;
else return 0;
}
//取栈顶元素(只取不删)
int GetTop(SqStack p)
{
if (p.top == p.base) return ERROR;
else return *(p.top - 1);
}
//插入元素e到栈顶
int Push(SqStack p, int e)
{
if (p->top - p->base >= p->stacksize)
{
p->base = (int)malloc(sizeof(int) * (p->stacksize + STACKINCREASE));
if (!p->base) exit(OVERFLOW);
p->stacksize = p->stacksize + STACKINCREASE;
}
(p->top) = e;
p->top++;
return OK;
//(p->top)++ = e;
}
//删除栈顶元素
int Pop(SqStack *p)
{
if (p->base == p->top) return ERROR;
p->top--;
return OK;
}
//数值转换
void conversion()
{
SqStack s;
InitStack(&s);
int n, m;//n是输入的十进制数,m是需要转换的进制
scanf_s("%d %d", &n, &m);
while (n)
{
Push(&s, n%m);
n = n / m;
}
while (!StackEmpty(s))
{
printf("%d", GetTop(s));
Pop(&s);
}
}
int main()
{
conversion();
}