链表的插入功能实现如下:
查找符合的插入位置:
1. 链表为空,把插入链表当成头节点
2. 查到位置为链表的中间元素
3. 没查到位置,加到链表的末尾
4. 查到位置为链表的头节点
这里插入规则是按学号从小到大插入。
#include <iostream>
#include<stdio.h>
#include<malloc.h>
using namespace std;
struct stu{
int Inum;
double Dscore;
char Cname[30];
struct stu *Snext;
};
int main()
{
struct stu *head, *tail, *newstu, *p;
void List(struct stu *);
struct stu *Insert(struct stu *,struct stu *);
head = tail = NULL;
int Inum;
printf("请输入要插入的数据(学号 成绩 姓名)如要结束输入,请输入学号为0\n");
scanf("%d",&Inum);
while(Inum)
{
newstu = (struct stu *)malloc(sizeof(struct stu));
newstu->Inum = Inum;
scanf("%lf",&newstu->Dscore);
scanf("%s",&newstu->Cname);
head = Insert(head,newstu);
scanf("%d",&Inum);
}
List(head);
return 0;
}
struct stu *Insert(struct stu *head, struct stu *newstu)
{
struct stu *p, *last;
p = head;
if(p == NULL)//对应第一种情况
{
head = newstu;
head->Snext = NULL;
}
else
{
while((p != NULL) &&(p->Inum <= newstu->Inum))
{
last = p;
p = p->Snext;
}
if(p != NULL)
{
if(head == p)//对应第四种情况
{
head = newstu;
newstu->Snext = p;
}
else//对应第三种情形
{
newstu->Snext = last->Snext;
last->Snext = p;
}
}
else//对应第二种情形
{
last->Snext = newstu;
newstu->Snext = NULL;
}
}
return head;
}
void List(struct stu *head)
{
struct stu *p;
printf("您输入的链表为:\n");
p = head;
if(p != NULL)
{
while(p != NULL)
{
printf("%d\t%lf\t%s\n",p->Inum,p->Dscore,p->Cname);
p = p->Snext;
}
}
else
{
printf("此链表为空");
}
}