请各位C++爱好者,帮忙看一下,我的这个程序。出什么问题了啊?为什么不能输出逆置前后的内容呢?

来源:百度知道 编辑:UC知道 时间:2024/05/22 20:25:59
#include<iostream.h>
struct node
{ char data;
struct node *next;
};
typedef struct node *link;
class Tdlb
{
private:
link head;
public:
Tdlb(char a[],int n);
void inver();
void print();

};

Tdlb::Tdlb(char a[],int n)
{
link p;
int i;
head=new node; head->next=NULL;
for (i=n-1;i>=0;i--)
{
p=new node;p->data=a[i];
p->next=head->next;head->next =p;
}
};

void Tdlb::inver()
{
link p,s;
p=head->next;head->next=NULL;
while (p!=NULL)
{
s=p;p=p->next;
s->next=head->next;head->next=s;
}
}

void Tdlb::print()
{
for(head=head->next;head!=NULL;head=head->next)
cout<< head->data;

楼上几位都没有说对. 此C++程序没有编译上的任何语法错误.所指出的所谓错误根本不存在. new不专属于pascal, C++中就是malloc的效果;Tdlb::Tdlb()中的i也初始化了;C++也和C一样使用typedef 和 struct node *next.

主要问题在于ex.print(): 第一次执行ex.print()时,就把head改得一塌糊涂了, 而后在ex.inver()中那个head早已面目全非了, 不出错反而奇怪了.
所以ex.print()中不应该变动head. 试试这样:

void Tdlb::print()
{
link p;
for(p=head->next;p!=NULL;p=p->next)
cout<< p->data;
cout<<endl;
}

注意整个程序还有需要优化和改进的地方.

Tdlb::Tdlb(char a[],int n)
是这里面的 i 没有初始化
上楼的不是学C++的
不过,typedef 和
struct node *next;
是 C 里有这样用法
C++不是这样用的

友情提醒:typedef用错地盘了!!应该放在结构体体之前

你的问题是:head=new node; new是什么意思,这是pascal中的!

应该是head=(node*)malloc(sizeof(struct node))