学术休假日 项目1-动态链表体验6
学术休假期 项目1-动态链表体验6
/* *Copyright (c)2014,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:test.cpp *作 者:冷基栋 *完成日期:2015年1月24日 *版 本 号:v1.0 * *问题描述:编写函数,使建立链表时,结点中的数据呈现升序,插入一个数到有序链表中并按原序排列。 *程序输入:若干正数(以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( ) { int n; make_list(); cout<<"插入一个数:"; cin>>n; insert(n); out_list(); return 0; } void make_list() { int n; Node *p,*q,*t; cout<<"输入若干正数(以0或一个负数结束)建立链表:"; 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 insert(int n) { Node *p,*q,*t; 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; } } } } void out_list() { Node *p=head; cout<<"链表中的数据为:"<<endl; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; return; }
运行结果:
/* *Copyright (c)2014,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:test.cpp *作 者:冷基栋 *完成日期:2015年1月24日 *版 本 号:v1.0 * *问题描述:编写函数,使建立链表时,结点中的数据呈现升序,插入一个数到有序链表中并按原序排列。 *程序输入:若干正数(以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( ) { int n; make_list(); cout<<"插入一个数:"; cin>>n; insert(n); out_list(); return 0; } void make_list() { int n; Node *p,*q,*t; cout<<"输入若干正数(以0或一个负数结束)建立链表:"; cin>>n; while(n>0) //输入若干正数建立链表,输入非正数时,建立过程结束 { insert(n); cin>>n; //输入下一个数,准备建立下一个结点 } return; } void insert(int n) { Node *p,*q,*t; 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; } } } } void out_list() { Node *p=head; cout<<"链表中的数据为:"<<endl; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; return; }
运行结果:
知识点总结:
在有序链表中插入一个结点
学习心得:
好好学习 天天向上