我在书上看到这样一串代码
struct stu * insert(struct stu * head,struct stu *pi)
{
struct stu *pb,*pf;
pb=head;
if(head==NULL) /*链表为空*/
{
head=pi;
}
else
{
while((pi->num>pb->num)&&(pb->next!=NULL)) /*查找插入的位置*/
{
pf=pb;
pb=pb->next;
}
if(pi->num<=pb->num)
{
if(head==pb) /*在第一个结点前面插入*/
{
head=pi;
}
else /*在链表中间插入*/
{
pf->next=pi;
pi->next=pb;
}
}
else
{
pb->next=pi; /*在链表结尾插入*/
pi->next=NULL;
}
}
return head;
}
我的问题在这一段代码
if(head==pb) /*在第一个结点前面插入*/
{
head=pi;
}
这里书上的定义是在第一个结点前面插入,但是如果想要执行到这一段的函数需要满足head==pb和pi->num<=pb->num两个条件,就是pi->num在最初设定的时候就小于或者等于head->num
满足这样的条件假设head->num=0,pi->num=0或者head->num=1,pi->num=0那这串代码不是应该写成head=pi; pi->next=pb;吗
而且我在执行这段代码的时候,发现不管是我把pi->num设置的比head->小或者是相等,都没有办法把pi插入到head前面,运行插入后的结果一直与插入前的结果一致,就好像这一段问题代码从来没有执行过。
所以单链表最初的head值前是无法在插入吗?还是我的这段代码其实是有问题的?
我整个执行程序的代码在下面:
#include<stdio.h>
#include<stdlib.h>
struct stu
{
int num;
struct stu *next;
};
struct stu * creat(int n)
{
struct stu *p,*h,*s;
int i;
if((h=(struct stu *)malloc(sizeof(struct stu)))==NULL)
printf("不能分配内存空间!");
h->num=0;
h->next=NULL;
p=h;
for(i=0;i<n;i++)
{
if((s=(struct stu *)malloc(sizeof(struct stu)))==NULL)
printf("不能分配内存空间!");
p->next=s;
printf("请输入第%d个数字:",i+1);
scanf("%d",&s->num);
s->next=NULL;
p=s;
}
return(h);
}
struct stu * insert(struct stu * head,struct stu *pi)
{
struct stu *pb,*pf;
pb=head;
if(head==NULL)
{
head=pi;
}
else
{
while((pi->num>pb->num)&&(pb->next!=NULL))
{
pf=pb;
pb=pb->next;
}
if(pi->num<=pb->num)
{
if(head==pb)
{
head=pi;
}
else
{
pf->next=pi;
pi->next=pb;
}
}
else
{
pb->next=pi;
pi->next=NULL;
}
}
return head;
}
void output(struct stu *h)
{
struct stu *p;
p=h;
while(p->next!=NULL)
{
printf("%d \n",p->num);
p=p->next;
}
printf("%d \n",p->num);
}
void main()
{
int number;
struct stu *head,*pi;
printf("请输入链表长度:");
scanf("%d",&number);
head=creat(number);
output(head);
pi=(struct stu *)malloc(sizeof(struct stu));
printf("请输入插入数值:");
scanf("%d",&pi->num);
pi->next=NULL;
insert(head,pi);
output(head);
}