题目:
使用链式栈,实现十进制转八进制:键盘输入一个十进制数,经过链式栈的相关算法,输出八进制数。
代码:
#include <stdio.h>
//链式栈节点
typedef struct node
{
//数据域
int data;
struct node *next;
} Node;
//链式栈管理结构体
typedef struct linkStack
{
int size;
Node *top;
} Linkstack;
//初始化空栈
Linkstack *Initstack()
{
Linkstack *s = (Linkstack *)malloc(sizeof(Linkstack));
if (s != NULL)
{
s->top = NULL;
s->size = 0;
}
return s;
}
//判断栈是否为空
int ifNULL(Linkstack *s)
{
if (s->size == 0)
return 1;
else return 0;
}
//取栈顶元素
int top(Linkstack *s, int *p)
{
if (ifNULL(s))
return 0;
*p = s->top->data;
return 1;
}
//出栈
int Pop(Linkstack *s)
{
if (ifNULL(s))
return 0;
//取栈顶元素的地址
Node *pm = s->top;
//将原栈顶元素剔除出栈
s->top = pm->next;
//pm->next = NULL;
//*p = pm->data;
free(pm);
return 1;
}
//入栈
int Push(Linkstack *s, int data)
{
Node *new = (Node *)malloc(sizeof(Node));
if (new != NULL)
{
new->data = data;
new->next = s->top;
s->top = new;
s->size++;
return 1;
}
}
int main()
{
int a, tmp, data;
Linkstack *s = Initstack();
printf("输入十进制整数:");
scanf("%d", &a);
while (a)
{
tmp = a % 8;
Push(s, tmp);
a = a / 8;
}
printf("八进制数:");
while(!ifNULL(s))
{
printf("%d", s->top->data);
Pop(s);
}
return 0;
}