第十八周项目一(6):将值为x的结点插入到建立起来的有序链表中
2015-01-31 19:47
204 查看
问题及代码:
运行结果:
学习心得:
在上一篇的基础上,对make_list进行修改,添加了自定义函数insert。
/* *Copyright (c)2014,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:动态链表体验.cpp *作 者:白云飞 *完成日期:2015年1月31日 *版 本 号:v1.0 * *问题描述:编写函数void insert(int x),将值为x的结点插入到由make_list建立起来的有序链表中。 *程序输入:输入若干正数(以0或一个负数结束)建立链表。 *程序输出:输出升序后的所有的数。 */ #include <iostream> using namespace std; struct Node { int data; //结点的数据 struct Node *next; //指向下一结点 }; Node *head=NULL; //将链表头定义为全局变量,以便于后面操作 void make_list(); //建立链表 void out_list(); //输出链表 void insert(int x); //排序 int main( ) { make_list(); out_list(); int x; cout<<"请输入要插入的数:"; cin>>x; insert(x); out_list(); return 0; } void make_limake_listst() { int n; cout<<"输入若干正数(以0或一个负数结束)建立链表:"; cin>>n; while(n>0)//输入若干正数建立链表,输入非正数时,建立过程结束 { insert(n);//调用insert cin>>n; } return; } void out_list() { Node *p=head; cout<<"链表中的数据为:"<<endl; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; return; } void insert(int x) { Node *p,*q,*f; p=new Node; //新建结点 p->data=x; p->next=NULL; if(head==NULL) head=p; else { if(head->data>x) { p->next=head; head=p; } else { f=head; q=f->next; while(q!=NULL&&x>q->data) { f=q; q=f->next; } if(q==NULL) { f->next=p; } else { p->next=q; f->next=p; } } } return; }
运行结果:
学习心得:
在上一篇的基础上,对make_list进行修改,添加了自定义函数insert。
相关文章推荐
- 将节点插入到建立起来的有序链表中
- 从键盘读入n个整数(升序),请编写算法实现: 建立带表头结点的单链表; 显示单链表,(形如:H->10->20->30->40); 在有序单链表中插入新的数据元素x; 将单链表就地逆
- 向头指针为 L的有序单链表(从小到大有序)中插入一个结点,使插入后链表仍然有序
- 单链表的建立(头部延长、尾部延长)、插入操作、删除操作(无头结点的删除、有头结点的删除)
- 输入一组整型元素序列,使用尾插法建立一个带有头结点的单链表。 ② 实现该线性表的遍历。 ③ 在该单链表的第i个元素前插入一个整数。 ④ 删除该单链表中的第i个元素,其值通过参数将其返回。 ⑤ 建立两个
- 链表的基本操作(创建,查找指定位置元素,删除指定元素,插入,倒置,去重,求集合的差,分别交换结点与交换结点值实现的冒泡排序,将两个有序链表合并成一个有序链表)c语言实现
- 建立一个带附加头结点的单链表.实现测长/打印/删除结点/插入结点/逆置/查找中间节点/查找倒数第k个节点/判断是否有环
- 编写算法实现建立一个带头结点的含n个元素的双向循环链表H,并在链表H中的第i个位置插入一个元素e
- 数据结构与算法分析笔记与总结(java实现)--链表9:有序环形链表中插入新结点问题
- 有序链表插入新结点的改进
- 双向循环链表的建立,插入,删除(不带头结点)
- 数据结构——单链表的创建、逆置、插入、有序表的建立、有序单链表合并等基础操作!!
- 第十八周项目一(2):输出链表中是否有值为x的结点
- 第十九周项目一:动态链表体验(六):将值为X的结点插入到升序的链表中
- 在一个递增有序链表中插入新结点并保持链表递增顺序不变
- 双链表的建立、求长、定位、插入、删除、输出和释放(带头结点且成环状)
- c++链表 建立 输入 输出 删除结点 插入结点 释放链表 的函数
- 第十八周项目1-6:合适位置插入结点
- 第十八周项目一(1):后输入的数据,将新输入的数字对应的结点放在链表末尾
- (2)单链表的操作 ① 输入一组整型元素序列,使用尾插法建立一个带有头结点的单链表。 ② 实现该线性表的遍历。 ③ 在该单链表的第i个元素前插入一个整数。 ④ 删除该单链表中的第i个元素,其值通过参数