有序链表的建立

这里的change函数是通过冒泡的方式来排序的
两个for循环,在链表中实现
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
void creat(int n,struct node *&head)
{
int i;
struct node *tail,*p;
head=(struct node *)malloc(sizeof(struct node ));
head->next=NULL;
tail=head;
for(i=0;i<n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
};
void show(struct node *head)
{
struct node *p;
p=head->next;
while(p)
{
if(!p->next)
{
printf("%d\n",p->data);
}
else
{
printf("%d ",p->data);
}
p=p->next;
}
}
void change(struct node *&head)
{
struct node *p,*q;
for(p=head->next;p;p=p->next)
{
for(q=p->next;q;q=q->next)
{
if(p->data>q->data)
{
int t;
t=p->data;
p->data=q->data;
q->data=t;
}
}
}
}
int main()
{
struct node *head;
int n;
scanf("%d",&n);
creat(n,head);
change(head);
show(head);
}
Fork me on GitHub