C++问题,高手进

#include <iostream.h>
#include <stdlib.h>
typedef struct node{

char data;
node *next;
}stack;
stack* push(stack *top,char d)
{
stack *p;
p=new stack;
if(p)
{
p->data=d;
p->next=top;
top=p;
return top;
}
else
{
cout<<"空间不足!!"<<endl;
exit(0);
}

}
char pop(stack* top)
{
char temp;
if(top==NULL)
{
cout<<"栈已空!!"<<endl;
exit(0);
}
else
{
temp=top->data;
top=top->next;
return temp;

}
}
void main()
{
stack *top;
top=NULL;
char temp;
push(top,'a');
temp=pop(top);
if(temp=='a')
{
cout<<"是回文字符串!"<<endl;
}
else
{
cout<<"不是回文字符串!"<<endl;
}

}

初学C++,也有一段时间没碰C++了,写了上面这段代码,不知道哪里出问题
问题很简单,输入一个字符串到一个栈里,在利用栈的性质判断是不是回文字符串
也许是我语法格式上有错,我把typedef 这个语句去掉后,直接用node声明top就没问题,而用stack申明时,我这样输入top-> 后面居然弄出一堆东西。。。不是应该只有data 和next么???
请各位帮忙找错误,再告诉我top-> 后面怎么会有这么多东西
谢谢!
top的传递是有问题,我照我们书上打的,这本教材很烂。
后面一堆东西如图,我不把node命名为stack后就没有了,这是怎么回事?

这是c和c++语言冲突的问题。

你在定义栈的时候用的是new,这是c++的语法,可你定义stack确是用的typedef,这是c的用法。

如果用c++,那你定义stack的时候,不用typedef,这样系统认为这是c++中的结构体或者是类。

如果用c,那你不能用new,而应该用p=(stack*)malloc(n*sizeof(stack));其中n是开辟栈的空间大小。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-05-23
在我这后面只有data,next啊,清理工程,重新编译试试吧
第2个回答  2010-05-23
push(&top,'a');

stack* push(stack **top,char d)
{
stack *p;
p=new stack;
if(p)
{
p->data=d;
p->next=*top;
*top=p;
return *top;
}
else
{
cout<<"空间不足!!"<<endl;
exit(0);
}
}
传入的TOP 和形参TOP 是两个变量 PUSH里的TOP变了 不影响外部TOP
而且你调用PUSH的时候也没接返回值
我没试输入 不过你说后边一堆东西 估计也是指针传递的问题
输出野指针一般不是都乱码么
第3个回答  2010-05-24
你看看这个程序,也是写的回文字符串。你那top可能是你编译器错把它当stack来用了。我在vs2005上后面只出现了data和next。
#include<stdio.h>
#include<conio.h>
#define SIZE 20
int isPalindrome(char []); /* Prototype only send the number and type of arguments to the Compiler. */

main()
{ /*Local Declarations*/
char str[SIZE];
/*Statements*/
printf("请输入字符串,以回车结束:\n");
scanf("%s",str); /*Record the string.*/
if(isPalindrome(str)==0) /*The string is not a palindrome.*/
{ printf("The string is not a palindrome.\n"); }
else /*The string is a palindrome.*/
{ printf("The string is a palindrome.\n"); }
system("pause");
return 0;
}

int isPalindrome(char array[])
{
int i,num_str=0;
for(i=0;array[i]!='\0';i++)/*Count how many characters there are in the string.*/
{ num_str++; }
i=0;
while((array[0+i]==array[num_str-i-1])&&(i<num_str/2))
{ i++; }
if(i==num_str/2) /*Compare until the middle two.*/
return 1;
else
return 0;
}
相似回答