问题及代码
/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:辛彬
* 完成日期:2015 年 1 月 30 日
* 版 本 号:v1.0
*
* 问题描述:编写make_list3()函数建立链表,使建立链表时,使结点中的数据呈现升序。
* 输入描述:一些整数。
* 程序输出:整理后的链表。
*/
#include <iostream>
using namespace std;
struct Node
{
int data; //结点的数据
struct Node *next; //指向下一结点
};
Node *head=NULL; //将链表头定义为全局变量,以便于后面操作
void delete_node(int x); //删除链表
void make_list3();
void out_list();
int main( )
{
make_list3();
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=q->next;
}
if(q==NULL)
p->next=t;
else
{
t->next=q;
p->next=t;
}
}
}
cin>>n;
}
q=p->next;
p=head;
return;
}
void out_list()
{
Node *p=head;
cout<<"链表中的数据为:"<<endl;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return;
}
运行结果:
学习感悟:果然boss就是boss的思维,我一开始想先把输入的数保存进链表,再排序,但想到排序时难改变链表里的地址。看到了贺老的方法,先把第一个输入的数做表头,通过p和q这对基友的向后走,将接下来输入的数放在他们中间,从而达到排序的效果,不得不说这思维。。。。