头插,尾插,插入,删除,查找,长度
1.头插·
在链表的前面插数,可理解为反向输出
void createbyhead(linklist head)
{
node*s;
char name[20];
int num;\
while(1)
{
scanf("%s",name);
scanf("%d",num);
if(num==0)
break;
else
{
s=(node*)malloc(sizeof(node));
strcpy(s->name,name);
s->num=num;
s->next=head->next;
head->next=s;
}
}
2.尾插(其实和头插区别不大)
void createbyrear(linklist head)
{
node*s;
char name[20];
int num;
while(1)
{
scanf("%s",name);
scanf("%d",num);
if(num==0)
break;
else
{
s=(node*)malloc(sizeof(node));
strcpy(s->name,name);
s->num=num;
head->next=s;
head=s;
}
}
head->next=NULL;
}
☆可以把尾插想象成一个没有底的桶,进去是什么样,出来还是什么样。
可以把头插想象成一个有底的桶,先进去的水,后出来。
3.插入
void insert(linklist head,int c)
{
node*p=head,*s;
int j=0;
printf(" 你要插到第 %d 的后面",c);
while(j<c-1&&p)
{
p=p->next;
j++
}
if(p)
{
s=(node*)malloc(sizeof(node));
printf("输入插入人的名字和学号");
scanf("%s",s->name);
scanf("%d",&s->num);
s->next=p->next;
p->next=s;
}
}
4.删除
void delete(linklist head ,int c)
{
node*p=head,*q;
int j=0;
printf("要删的信息是第 %d 个",c);
while(p&&j,c-1)
{
j++;
p=p->next;
}
if(p!=NULL&&p->next!=NULL)
{
q=p->next;
p->next=q->next;
free(q);
}
}
不难看出,删除和插入是一组的,函数参数都有2个,有2个变量,先定位,后操作
5,查找
node* search(linklist head,char name[])
{
node *p=head->next;
while(strcmp(p->name,name)!=0)
p=p->next;
if(p==NULL)
printf("无");
return p;
返回值是指针,为了定位。比大小是为了定位。
6.长度
void length(linklist)
{
int count;
node *s=head->next; //加next 是为了错过 Num==0 的数
while(s)
{
count++;
s=s->next;
}
printf("长度是 %d",count);
}
长度和普通计数一样,注意要加 next ,不用申请空间,因为没有scanf。