写的一个简单的链表程序,有异常 !
写的一个简单的链表程序,有错误 求助!!
在creat函数里面 return head的时候提示错误cannot convert from 'struct node *' to 'struct node' 求高手修改。。。
#include <iostream.h>
#include <malloc.h>
struct node
{
int data;
struct node *next;
};
struct node creat(struct node *head)
{
struct node *pas,*p;
head=p=NULL;
int x;
cout<<"Enter an integer:";
cin>>x;
while(x!=0)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=x;
p->next=NULL;
if(head==NULL)
head=pas=p;
else
{
pas->next=p;
pas=p;
}
cout<<"Enter another integer:";
cin>>x;
}
return head;
}
void main()
{
struct node *head=NULL;
creat(head);
cout<<"data of the first node:"<<head->data<<endl;
cout<<"data of the second node:"<<head->next->data<<endl;
}
------解决方案--------------------
在creat函数里面 return head的时候提示错误cannot convert from 'struct node *' to 'struct node' 求高手修改。。。
#include <iostream.h>
#include <malloc.h>
struct node
{
int data;
struct node *next;
};
struct node creat(struct node *head)
{
struct node *pas,*p;
head=p=NULL;
int x;
cout<<"Enter an integer:";
cin>>x;
while(x!=0)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=x;
p->next=NULL;
if(head==NULL)
head=pas=p;
else
{
pas->next=p;
pas=p;
}
cout<<"Enter another integer:";
cin>>x;
}
return head;
}
void main()
{
struct node *head=NULL;
creat(head);
cout<<"data of the first node:"<<head->data<<endl;
cout<<"data of the second node:"<<head->next->data<<endl;
}
------解决方案--------------------
- C/C++ code
//按照C++语言改写了一下 #include <iostream> using namespace std; typedef struct node { int data; struct node *next; }node,*linklist; void creat(linklist &head) //此次用引用才能改变head { node *pas,*p; p=NULL; int x; cout<<"Enter an integer:"; cin>>x; while(x!=0) { //p=(struct node *)malloc(sizeof(struct node)); p=new node; p->data=x; p->next=NULL; if(head==NULL) { head=p; pas=head; } else { pas->next=p; pas=p; } cout<<"Enter another integer:"; cin>>x; } } int main() { linklist head=NULL; creat(head); cout<<"data of the first node:"<<head->data<<endl; cout<<"data of the second node:"<<head->next->data<<endl; system("pause"); return 0; }
------解决方案--------------------
- C/C++ code
//用函数的返回值 #include <iostream> using namespace std; typedef struct node { int data; struct node *next; }node; node* creat(node* head) { node *pas,*p; p=NULL; int x; cout<<"Enter an integer:"; cin>>x; while(x!=0) { //p=(struct node *)malloc(sizeof(struct node)); p=new node; p->data=x; p->next=NULL; if(head==NULL) { head=p; pas=head; } else { pas->next=p; pas=p; } cout<<"Enter another integer:"; cin>>x; } return head; } int main() { node *head=NULL; head=creat(head);//此处调用的时候要有返回值 cout<<"data of the first node:"<<head->data<<endl; cout<<"data of the second node:"<<head->next->data<<endl; system("pause"); return 0; }