数据结构之链表的插入
发布日期: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秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
SpringMVC常用的注解有哪些?
2019-04-26
spring bean的生命周期
2019-04-26
计算机网络子网划分详解
2019-04-26
计算机网络生成树算法STP简介
2019-04-26
三郎数据结构算法学习笔记:哈希表查找
2019-04-26
三郎数据结构算法学习笔记:二叉树的三种遍历及增删改查
2019-04-26
三郎数据结构算法学习笔记:顺序存储二叉树
2019-04-26
三郎数据结构算法学习笔记:线索二叉树
2019-04-26
解释Spring支持的几种bean的作用域。
2019-04-26
Spring框架中都用到了哪些设计模式?
2019-04-26
什么是MyBatis?
2019-04-26
MyBatis的优点和缺点
2019-04-26
#{}和${}的区别是什么?
2019-04-26
LeetCode题解(1508):子数组和排序后的区间和(Python)
2019-04-26
LeetCode题解(1509):三次操作后最大值与最小值的最小差(Python)
2019-04-26
LeetCode题解(1510):石子游戏IV(Python)
2019-04-26
LeetCode题解(1497):检查数组对是否可以被k整除(Python)
2019-04-26
LeetCode题解(0781):森林中的兔子(Python)
2019-04-26
LeetCode题解(0930):和相同的二元子数组(Python)
2019-04-26
LeetCode题解(0939):最小面积矩形(Python)
2019-04-26