您的位置:首页 > 理论基础 > 数据结构算法

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

2017-09-26 18:42 381 查看

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

Time Limit: 1000MS
Memory Limit: 65536KB
SubmitStatistic

Discuss

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

不得使用数组!

Author

AC:

01
#include<bits/stdc++.h>
02
using
namespace
std;
03
 
04
struct
node
05
{
06
    
int
data;
07
    
node *next;
08
};
09
node *head,*tail,*p,*q;
10
 
11
void
creat(
int
n)
12
{
13
    
head=
new
node;
14
    
head->next=NULL;
15
    
tail=head;
16
    
for
(
int
i=0;i<n;i++)
17
    
{
18
        
p=
new
node;
19
        
cin>>p->data;
20
        
p->next=NULL;
21
        
tail->next=p;
22
        
tail=p;
23
    
}
24
}
25
 
26
void
del(
int
n) 
//链表的排序
27
{
28
    
for
(p=head->next;p!=NULL;p=p->next)
29
    
{
30
        
for
(q=p->next;q!=NULL;q=q->next)
31
        
{
32
            
if
(p->data>q->data)
33
            
{
34
                
int
temp=p->data;
35
                
p->data=q->data;
36
                
q->data=temp;
37
            
}
38
        
}
39
    
}
40
}
41
 
42
void
show(
int
n)
43
{
44
    
p=head->next;
45
    
while
(p!=NULL)
46
    
{
47
        
cout<<p->data;
48
        
if
(p->next!=NULL)
49
            
cout<<
" "
;
50
        
p=p->next;
51
    
}
52
    
cout<<endl;
53
}
54
 
55
int
main()
56
{
57
    
int
n;
58
    
cin>>n;
59
    
creat(n);
60
    
del(n);
61
    
show(n);
62
    
return
0;
63
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: