将新结点插入链表

来源:百度知道 编辑:UC知道 时间:2024/05/26 04:20:04
struct student *insert(struct student *head,struct student *new)
{
sturct student *p,*q;
p=q=head;
if(head==NULL)
{
head=new;
new->next=NULL;
}
else
{
while((new->num>p->num)&&(p->next!=NULL))
{
q=p;
p=p->next;
}
if(new->num<=p->num)
{
new->next=p;
if(head==p)
head=new;
else
q->next=new;
}
else
{
p->next=new;
new->next=NULL;
}
}
count++;
return(head);
}
这个能帮我看看吗?书上的,我这个从while后看不懂了。。。我总觉得这个程序是错的,,麻烦帮我讲一下好吗,我主要是他说的范围搞不懂,觉得超乱。。

struct student *insert(struct student *head,struct student *new)
{
sturct student *p,*q;
p=q=head;
if(head==NULL)//如果原来是空链表,则将新结点作为头结点
{
head=new;
new->next=NULL;
}
else//如果原来链表非空,则将新结点插入适当位置,使新链表数据仍保持升序
{
while((new->num>p->num)&&(p->next!=NULL))
{
//找到新结点应该插入的位置
//最终找到的位置应该在q和p之间
q=p;
p=p->next;
}
if(new->num<=p->num)
{
//找到了比新结点值大的结点,新结点应该插在此结点之前
new->next=p;
//如果新结点值比头结点值小,则新结点作为新的头结点
if(head==p)
head=new;
else
q->next=new;
}
else
//如果之前找插入位置的循环是因为已经找到链表尾而结束的
//那么将新结点放到链表尾部
{
p->next=new;
new->next=NULL;
}
}
count++;
return(head);
}

看程序代码不能只看代码,要先从逻辑上想好一个结点插入链表会有哪些情况,再去看代码印证你的想法.

//这程序你首先要明白各指针是什么意思!head,p,q,next
while((new->num>p->num)&&(p->next!=NULL))//为了寻找插入点
{
q=p;//指针q得到前一结点的地址