首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

写的一个简单的链表程序,有异常 !

2012-02-10 
写的一个简单的链表程序,有错误 求助!!在creat函数里面 return head的时候提示错误cannot convert from s

写的一个简单的链表程序,有错误 求助!!
在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;} 

热点排行