数据结构之链表的插入

插入结点:将一个结点插入到已有的链表中
插入原则:
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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值