数据结构实验之链表六:有序链表的建立
Problem Description
输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
Input
第一行输入整数个数N;
第二行输入N个无序的整数。
Output
依次输出有序链表的结点值。
Example Input
6
33 6 22 9 44 5
Example Output
5 6 9 22 33 44
Hint
不得使用数组!
//数据结构实验之链表六:有序链表的建立
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
node *creat(int n)//建表
{
node *l,*p,*s;
int i;
l=(node *)malloc(sizeof(node));
l->next=NULL;
p=l;
for(i=1;i<=n;i++)
{
s=(node *)malloc(sizeof(node));
scanf("%d",&s->data);
p->next=s;
p=s;
}
p->next=NULL;
return l;
}
node *paixu(node *l)
{
node *p,*q;
int t;//p指向头结点,q指向p的指针域,这就相当于链表中,前一个数字与后一个数字的比较,双重循环。
for(p=l->next;p->next!=NULL;p=p->next)
{
for(q=p->next;q!=NULL;q=q->next)
{
if(p->data>q->data)
{
t=q->data;
q->data=p->data;
p->data=t;
}
}
}
return l;
}
void shuchu(node *l)//输出数据
{
node *r;
r=l->next;
while( r && r->next)
{
printf("%d ",r->data);
r=r->next;
}
printf("%d\n",r->data);
}
int main()
{
node *l;
int n;
scanf("%d",&n);
l=creat(n);
l=paixu(l);
shuchu(l);
return 0;
}