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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

输入N个无序的整数,建立一个有序链表,链表中的结点按照数值非降序排列,输出该有序链表。

Input

第一行输入整数个数N;
第二行输入N个无序的整数。

Output

依次输出有序链表的结点值。

Sample Input

6
33 6 22 9 44 5

Sample Output

5 6 9 22 33 44

Hint

不得使用数组!Source


01	#include <stdio.h>
02	#include <string.h>
03	#include <stdlib.h>
04	struct node
05	{
06	    int data;
07	    struct node *next;
08	};
09	struct node *creat(int n)
10	{
11	    struct node *head,*tail,*p;
12	    int i;
13	    head=(struct node *)malloc(sizeof(struct node));
14	    head->next=NULL;
15	    tail=head;
16	    for(i=0;i<n;i++)
17	    {
18	        p=(struct node *)malloc(sizeof(struct node));
19	        scanf("%d",&p->data);
20	        p->next=NULL;
21	        tail->next=p;
22	        tail=p;
23	    }
24	    return head;
25	};
26	void sort(struct node *head,int n)
27	{
28	    struct node *p,*q;
29	    int t;
30	    for(p=head->next;p!=NULL;p=p->next)
31	    {
32	        for(q=p->next;q!=NULL;q=q->next)
33	        {
34	            if(p->data>q->data)
35	            {
36	                t=p->data;
37	                p->data=q->data;
38	                q->data=t;
39	            }
40	        }
41	    }
42	}
43	void show(struct node *head)
44	{
45	    struct node *p;
46	    p=head->next;
47	    while(p!=NULL)
48	    {
49	        if(p->next!=NULL)
50	            printf("%d ",p->data);
51	        else
52	            printf("%d\n",p->data);
53	        p=p->next;
54	    }
55	}
56	int main()
57	{
58	    int n;
59	    struct node *head;
60	    scanf("%d",&n);
61	    head=creat(n);
62	    sort(head,n);
63	    show(head);
64	    return 0;
65	}
66	
67	
68	/*************************************************


70	Result: Accepted
71	Take time: 0ms
72	Take Memory: 152KB
73	Submit time: 2018-08-01 16:31:12
74	****************************************************/
 

猜你喜欢

转载自blog.csdn.net/Allinone99/article/details/81333282
今日推荐