数据结构实验之链表六:有序链表的建立
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。
Input
第一行输入整数个数N;
第二行输入N个无序的整数。
Output
依次输出有序链表的结点值。
Sample Input
6
33 6 22 9 44 5
Sample Output
5 6 9 22 33 44
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat(int n)
{
int i;
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;//申请一个头节点让它为空,让尾指针指向
for(i=1; i<=n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;//p现在是一个存放了数据和指针的结点
tail->next=p;//要把p连接在链表中就要把p连接在尾结点之后,要连接尾结点和p,如果想要把尾结点和p连接在一起,那就要把p的地址记下来,用tail记p的地址,就是tail->next=p,这样就把p的地址记下来了,
tail=p; //连接起新的链表之后,就需要把尾结点放在最后,tail=p
}
return head;
};
void plus(struct node *head)
{
struct node *z,*q;
int t;
for(z=head->next; z!=NULL; z=z->next)
{
for(q=z->next; q!=NULL; q=q->next)//q始终存着z所指的地址
{
if(z->data>q->data)
{
t=z->data;
z->data=q->data;
q->data=t;//只需要交换数据
}
}
}
}
void print(struct node *head)
{
int n=0;
struct node *p;
p=head->next;
while(p)//只要p不为空
{
n++;
if(n==1)
printf("%d",p->data);
else
printf(" %d",p->data);//输出p所保存的数据,输出结束后指向下一个
p=p->next;
}
printf("\n");//n保证空格数量完全一致
}
int main()
{
int n;
scanf("%d",&n);
struct node *h1;
h1=creat(n);
plus(h1);
print(h1);
return 0;
}