帶頭結(jié)點的單鏈表如何判斷為空?
#include<iostream.h>
typedef char datatype;
typedef struct node *pointer;
struct node
{
datatype data;
pointer next;
};
typedef pointer lklist;
int insert(pointer head)
{
pointer q,s;
char x;
if(!head){cout<<"空表"<<endl;return 0;}//如果是空鏈表,為什么不能返回主函數(shù),而是出錯。
q=head;
q=q->next;
cin>>x;
s=new node;
s->data=x;
s->next=q->next;
q->next=s;
return 1;
}
lklist set(pointer head)
{
pointer rear,s;
char data;
char flag;
head=new node;
rear=head;
cin>>data;
while(1)
{
s=new node;
s->data=data;
rear->next=s;
rear=s;
cout<<"繼續(xù)?"<<endl;
cin>>flag;
if(flag=='n'||flag=='N')break;
cin>>data;
}
rear->next=NULL;
return head;
}
int show(pointer head)
{
if(!head){cout<<"空表"<<endl;return 0;}
head=head->next;
while(head!=NULL)
{
cout<<head->data<<endl;
head=head->next;
}
return 1;
}
void main()
{
pointer head=NULL;
int flag;
while(1)
{
cout<<"選擇"<<endl;
cin>>flag;
switch(flag)
{
case 1:head=set(head);break;
case 2:insert(head);break;//如果我一開始直接選插入就會出錯
case 3:show(head);break;
case 0:return;
}
}
}