寒假项目1-动态链表体验(改造)(6)
2015-01-23 10:16
260 查看
/* * Copyright (c) 2014, 烟台大学计算机学院 * All rights reserved. * 文件名称:test.cpp * 作 者:刘畅 * 完成日期:2015 年 1 月 23 日 * 版 本 号:v1.0 * * 问题描述:改造博文示例中的链表。 * 输入描述:输入n(n为结点数据)。 * 程序输出:输出动态链表
(6)编写函数void insert(int x),将值为x的结点插入到由make_list3建立起来的有序链表中。
#include <iostream> #include <cstdio> using namespace std; struct Node { int data; //结点的数据 struct Node *next; //指向下一个结点 }; Node *head=NULL; //将链表头定义为全局变量,以便后续操作 void make_list3(); //建立链表 void out_list(); //输出链表 void insert(int x); //将值为x的结点插入到有序链表中,使仍有序 int main() { int x; cin>>x; make_list3(); out_list(); insert(x); out_list(); return 0; } void make_list3() { int n; Node *p,*q,*t; cout<<"输入若干正数(以0或一个负数结束)建立链表:"<<endl; cin>>n; while(n>0) { t=new Node; t->data=n; t->next=NULL; if(head==NULL) head=t; else { if (n<=head->data) { t->next=head; head=t; } else { p=head; q=p->next; while (q!=NULL&&n>q->data) { p=q; q=p->next; } if (q==NULL) { p->next=t; } else { t->next=q; p->next=t; } } } 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 *q,*p,*t; t=new Node; t->data=x; t->next=NULL; if (head==NULL) head==t; else { if(x<=head->data) { t->next=head; head=t; } else { p=head; q=p->next; while(q!=NULL&&x>q->data) { p=q; q=p->next; } if(q==NULL) { p->next = t; } else { t->next=q; p->next=t; } } } cout<<"已插入新结点..."<<endl; return; }
运行结果:
相关文章推荐
- 寒假项目1-动态链表体验(改造)(1)
- 寒假项目1-动态链表体验(改造)(4)
- 寒假项目1-动态链表体验(改造)(5)
- 寒假项目1-动态链表体验(改造)(2)
- 寒假项目1-动态链表体验(改造)(3)
- 寒假14项目1——动态链表体验(修改2)
- 寒假项目1-动态链表体验(示例)
- 寒假14项目1——动态链表体验(示例)
- 第18周项目1-动态链表体验(4、删除特定的结点)
- 寒假14项目1——动态链表体验(修改1)
- 第三周项目1-动态链表体验(一)
- 第18周项目1-动态链表体验(2查找结点)
- 第19周上机实践项目1——动态链表体验(4)
- 学术休假期 项目1-动态链表体验3
- 第19周上机实践项目1——动态链表体验(5)
- 学术休假期 项目1-动态链表体验2
- 寒假14项目1——动态数组体验(修改3)
- 2014秋C++第19周 项目1参考 动态链表体验
- 学术休假期 项目1-动态链表体验5
- 学术休假期 项目1-动态链表体验1