/*
*Copyright(c)2014,烟台大学计算机学院
*All rights reserved.
*文件名称:test.cpp
*作者:满星辰
*完成日期:2014年 2月 4日
*版本号:v1.0
*问题描述:编写make_list3()函数建立链表,使建立链表时,使结点中的数据呈现升序。
*输入描述:链结的数据
*程序输出:
*/
#include <iostream>
using namespace std;
struct Node
{
int data; //结点的数据
struct Node *next; //指向下一结点
};
Node *head=NULL; //将链表头定义为全局变量,以便于后面
操作
void make_list3(); //建立升序链表
void out_list(); //输出链表
int main( )
{
make_list3();
out_list();
return 0;
}
void make_list3()
{
int n;
Node *p,*x,*y;
cout<<"输入若干正数(以0或一个负数结束)建立链表:";
cin>>n;
while(n>0)
{
p=new Node;
p->data=n;
p->next=NULL;
if(head==NULL)
{
head=p;
}
else
{
if(n<=head->data)
{
p->next=head;
head=p;
}
else
{
x=head;
y=x->next;
while(y!=NULL&&n>y->data)
{
x=y;
y=x->next;
}
if(y==NULL)
{
x->next=p;
}
else
{
p->next=y;
x->next=p;
}
}
}
cin>>n;
}
return;
}
void out_list()
{
Node *p=head;
cout<<"链表中的数据为:"<<endl;
if(p==NULL)
cout<<"空链表!";
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return;
}
示例图片:
学习心得:
表示真心不懂怎么在输入时就排序,这貌似是个一点都不复杂的数学问题?No!
恩恩,果然是我自己弱爆了。。。参考了下别人的程序,呵呵哒