数据结构实验之链表六:有序链表的建立
Time Limit: 1000ms Memory limit: 65536K
题目描述
输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
输入
第一行输入整数个数N;
第二行输入N个无序的整数。
第二行输入N个无序的整数。
输出
依次输出有序链表的结点值。
示例输入
6
33 6 22 9 44 5
6 33 6 22 9 44 5
示例输出
5 6 9 22 33 44
5 6 9 22 33 44
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head,*tail,*p,*q;
int n;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
scanf("%d",&n);
while(n--)
{
p=(struct node *)malloc(sizeof(struct node));
p->next=NULL;
scanf("%d",&p->data);
q=head->next;
tail=head;
while(q!=NULL)
{
if(p->data<q->data)
{
p->next=q;
tail->next=p;///将p插入
break;
}
tail=q;///*标记q的位置
q=q->next;///*若q->next==NULL,退出循环
}
if(q==NULL)
{
tail->next=p;
}
}
q=head->next;
while(q!=NULL)
{
if(q->next==NULL)
printf("%d\n",q->data);
else printf("%d ",q->data);
q=q->next;
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head,*tail,*p,*q;
int n;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
scanf("%d",&n);
while(n--)
{
p=(struct node *)malloc(sizeof(struct node));
p->next=NULL;
scanf("%d",&p->data);
q=head->next;
tail=head;
while(q!=NULL)
{
if(p->data<q->data)
{
p->next=q;
tail->next=p;///将p插入
break;
}
tail=q;///*标记q的位置
q=q->next;///*若q->next==NULL,退出循环
}
if(q==NULL)
{
tail->next=p;
}
}
q=head->next;
while(q!=NULL)
{
if(q->next==NULL)
printf("%d\n",q->data);
else printf("%d ",q->data);
q=q->next;
}
return 0;
}