插入结点:将一个结点插入到已有的链表中
插入原则:
1、插入操作不应破坏原链接关系
2、插入的结点应该在它该在的位置
实现方法:
应该有一个插入位置的查找子过程
共有三种情况:```
1、插入的结最小
2、插入的结点最大
插入原则:
1、插入操作不应破坏原链接关系
2、插入的结点应该在它该在的位置
实现方法:
应该有一个插入位置的查找子过程
共有三种情况:```
1、插入的结最小
2、插入的结点最大
3、插入的结在中间
同删除一样,需要几个临时指针:
P0: 指向待插的结点;初始化:p0=数组stu;
P1: 指向要在P1之前插入结点;初始化: p1=head;
P2: 指向要在P2之后插入结点;
插入操作:当符合以下条件时:p0->num 与 p1->num 比较找位置
if(p0->num>p1->num)&&(p1->next!=NULL) 则插入的结点不在p1所指结点之前;指针后移,交给p2;
p1= p1->next; p2=p1;
则继续与 p0 指向的数组去比,直到(p1->next!=NULL)为止。
否则有两种情况发生:
if(head==p1) head=p0;p0->next=p1插到原来第一个结点之前;
else p2->next=p0;p0->next=p1; 插到 p2 指向的结点之后;
还有另外一种情况:插到最后的结点之后;
p1->next=p0;p0->next=NULL;
代码实现:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct student
{
int num,score;
student *next;
};
struct student *insert(student *head,int num,int score)
{
struct student *p0,*p1,*p2;//p0指向待插入的节点,p1指向待插入节点之前的节点,p2指向待插入节点之后的节点
p2=head;
p0=new student;//p0=(struct student*)malloc(sizeof(struct student));
p0->num=num;
p0->score=score;
if(p2==NULL)
{
head=p0;
p0->next=NULL;
}
else
{
while(num>p2->num&&p2->next!=NULL)
{
p1=p2;
p2=p2->next;
}
if(num<=p2->num)
{
if(head==p2)
{
p0->next=head;
head=p0;
}
else
{
p1->next=p0;
p0->next=p2;
}
}
else
{
p2->next=p0;
p0->next=NULL;
}
}
while(head->next!=NULL)
{
cout<<head->num<<" "<<head->score<<endl;
head=head->next;
}
cout<<head->num<<" "<<head->score<<endl;
return head;
}
int main()
{
int num,score;
struct student a,b,c,d,e,*p,*head;
a.num=101;a.score=120;
b.num=102;b.score=121;
c.num=103;c.score=122;
d.num=105;d.score=124;
e.num=106;e.score=125;
head=&a;a.next=&b;b.next=&c;c.next=&d;d.next=&e;e.next=NULL;
cout<<"请输入要插入的学生的信息:";
cin>>num>>score;
insert(head,num,score);
return 0;
}