数据结构实验之链表六:有序链表的建立

来源:互联网 发布:北京宝库在线网络 编辑:程序博客网 时间:2024/05/16 19:47

输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
输入
第一行输入整数个数N;
第二行输入N个无序的整数。
输出
依次输出有序链表的结点值。
示例输入
6
33 6 22 9 44 5
示例输出
5 6 9 22 33 44
题解:说实在的这道题可以随意发挥,只要前面几道题都了解,这个也就很容易了,我是县建立了一个顺序表,然后用了for循环,你也可以先放到数组中,用sort()函数,在建立顺序表,随意选
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
int main()
{
int x,n,i,m;
cin>>n;
struct node *head,*tail,*p,*q;
head=new struct node();
head->next=NULL;
tail=head;
p=new struct node();
for(i=1;i<=n;i++)
{
cin>>x;
p->data=x;
p->next=NULL;
tail->next=p;
tail=p;
p=new struct node();
}
for(p=head->next;p!=NULL;p=p->next)
{
for(q=p->next;q!=NULL;q=q->next)
{
if(p->data>q->data)
{
m=p->data;p->data=q->data;q->data=m;
}
}
}
for(p=head->next;p!=NULL;p=p->next)
{
cout<<p->data<<" ";
}
return 0;
}

0 0
原创粉丝点击