关于链表的插入,删除,逆序的代码
// list.cpp : 定义控制台应用程序的入口点。//
#include "stdafx.h"
using namespace std;
#include "stdlib.h"
struct node
{int num;
struct node *next;
};
int n;
struct node * creat()
{struct node *head;
struct node *p1,*p2;
n=0;
p1=p2=(struct node *) malloc(sizeof(struct node));
cin>>p1->num;
head=NULL;
while(p1->num!=0)
{n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node *)malloc(sizeof(struct node));
cin>>p1->num;
}
p2->next=NULL;
return(head);
}
void print(struct node *head)
{
struct node *temp;
temp=head;
if(head != NULL)
do{
cout<<temp->num<<" ";
temp=temp->next;}while(temp!=NULL);
}
struct node * del(struct node * head,int num)
{
struct node *p1,*p2;
if(head==NULL){cout<<"这是个空链表"<<endl;goto end;}
p1=head;
while(num !=p1->num&&p1->next !=NULL)
{p2=p1;p1=p1->next;}
if(num==p1->num)
{if(p1==head)head=p1->next;
else p2->next=p1->next;
cout<<"成功删除"<<n<<endl;
n=n-1;
}
else cout<<"找不到要删除的数"<<endl;
end: return(head);
}
struct node * insert(struct node * head,struct node * point)
{struct node *p0,*p1,*p2;
int d;
cout<<"请输入要插入的位置"<<endl;
cin>>d;
p1=head;
p0=point;
if(head==NULL){head=p0;p0->next=NULL;}
else {while(!(d=p1->num&&p1->next!=NULL))
{p2=p1;p1=p1->next;}}
if(head==p1){head=p0;p0->next=p1;}
else if(p1->next==NULL){p0->next=NULL;p1->next=p0;}
else p0->next=p1;p2->next=p0;
n=n+1;
return(head);
}
struct node * back(struct node * head)
{struct node *p,*q,*r;
p=head;
q=p->next;
while(q!=NULL)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
head->next=NULL;
head=p;
return head;
}
void main()
{struct node *head,*point;
int c;
cout<<"please input num"<<endl;
head=creat();
print(head);
cout<<endl;
cout<<"input delete num"<<endl;
cin>>c;
while(c!=0)
{head=del(head,c);
print(head);
cout<<endl;
cout<<"input delete num2"<<endl;
cin>>c;
if(c==0)
goto ins;
}
ins:point=(struct node *)malloc(sizeof(struct node));
cout<<endl;
cout<<"输入要插入的数"<<endl;
cin>>point->num;
while(point->num!=0)
{head=insert(head,point);
print(head);
cout<<endl;
point=(struct node *)malloc(sizeof(struct node));
cout<<"输入要插入的数"<<endl;
cin>>point->num;
if(point->num==0)
goto back;
}
back:back(head);
print(head);
}
不清楚错误在哪里,有高手可以帮忙改过来吗?