单链表的操作注意事项:
1)输入链表头节点检验是否为空;
2)链表的遍历注意要前一节点的保存,以便插入或删除操作;
3)循环条件中注意p->next!=NULL条件使用。
#include<iostream>
using namespace std;
typedef struct node
{
int data;
node *next;
}node;
node *Creat()
{
node *head,*p,*s;
int x;
head=(node *)malloc(sizeof(node));
p=head;
int cycle=1;
while(cycle)
{
cout<<"请输入一个数:"<<endl;
cin>>x;
if (x!=0)
{
s=(node *)malloc(sizeof(node));
s->data=x;
p->next=s;
p=s;
}
else
{
p->next=NULL;
cycle=0;
}
}
head=head->next;
return head;
}
int length(node *head)
{
int n=0;
node *p;
p=head;
while (p!=NULL)
{
n++;
p=p->next;
}
return n;
}
void print(node *head)
{
node *p;
p=head;
int n;
n=length(head);
cout<<"链表中有"<<n<<"个记录!"<<endl;
if (p!=NULL)
{
while (p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
}
node *del(node *head,int num)
{
node *p,*s;
p=head;
while (p->data!=num&&p->next!=NULL)
{
s=p;
p=p->next;
}
if (num==p->data)
{
if(p==head)
{
p=p->next;
head=p;
free(p);
}
else
{
s->next=p->next;
free(p);
}
}
else
cout<<"没有找到"<<num<<endl;
return head;
}
node *insert(node *head,int num)
{
node *p,*s,*n;
p=head;
n=(node *)malloc(sizeof(node));
n->data=num;
while (num>p->data&&p!=NULL)
{
s=p;
p=p->next;
}
if (num<=p->data)
{
if (head==p)
{
n->next=p;
head=n;
}
else
{
n->next=p;
s->next=n;
}
}
else
{
p->next=n;
n->next=NULL;
}
return head;
}
void main()
{
node *head=Creat();
print(head);
// del(head,3);
head=insert(head,4);
print(head);
}