读书人

用栈实现数值转换的有关问题

发布时间: 2012-02-27 10:00:22 作者: rapoo

用栈实现数值转换的问题
想用栈实现,、十进制八进制之间的数值转换。我写的如下
include <stdio.h>
#define NULL 0
typedef int datatype;
typedef struct node
{ datatype data;
struct node *next;
} linkstack;

int EMPTY(linkstack *s)
{
if (s)
return(0);
else return(1);
}
linkstack *PUSH(linkstack *top, datatype x)
{
linkstack *p;
p=(linkstack*)malloc(sizeof(linkstack));
p-> data=x; p-> next=top;
top=p;
return top;
}
linkstack *POP(linkstack *top, datatype *x)
{ linkstack *p;
if (top==NULL)
{printf( "overflow\n "); return NULL;}
else
{ *x=top-> data;
p=top;
top=top-> next;
free(p);
return top;

}
}
void InitStack(linkstack *s)
{s=NULL;
}

main()
{int n,e;
linkstack *s;

InitStack(s);
scanf( "%d ",&n);
while(n){
Push(s,n%8);
n=n%8;
}
printf( "the result is: ");
while (!EMPTY(s)){
Pop(s,&e);
printf( "%d ",e);
}
}
可为什么总说s在InitStack里没有用?

[解决办法]
你这个实现有点问题,首先需要说的是

你的 main 函数的对转换的处理:

while(n){
Push(s,n%8);
n=n%8;
}
这个明显是错的,哪个老师也不能教给你这样来转换进制呀。

应该改为:
while(n){
Push(s,n%8);
n=n%8;
}

你的程序里最大的问题就是用单向链表的形式来实现了堆栈,
这也就是说,你只知道next,而不知道 pre 。
当出栈的时候的处理,明显有误,top = top-> next;这是得不到
比当前出栈元素提前入栈的元素的。
楼主仍然需要好好改改的了,或者想想其他办法。

PS:一般情况下,建议使用数组、top、bottom 来实现栈。

读书人网 >C语言

热点推荐