数据结构之链表的插入
发布日期:2022-02-02 02:58:08 浏览次数:23 分类:技术文章

本文共 1599 字,大约阅读时间需要 5 分钟。

插入结点:将一个结点插入到已有的链表中
插入原则:
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 
#include
#include
#include
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<
num<<" "<
score<
next; } cout<
num<<" "<
score<
>num>>score; insert(head,num,score); return 0;}

转载地址:https://blog.csdn.net/u010368749/article/details/19158263 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:数据结构之链表的删除
下一篇:数据结构之约瑟夫问题---猴子选大王

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月15日 09时24分16秒