对一个带头结点的单链表进行排序,使其按key值递增的顺序进行就地排序。
#include
#include
#include
typedef struct LNode {
int key;
struct LNode *next;
} LNode, *LinkList;
bool InitList(LinkList &L) {
L = (LNode *) malloc(sizeof(LNode));
if (L == NULL) {
return false;
}
L->next = NULL;
return true;
}
bool Empty(LinkList &L) {
return (L->next == NULL);
}
bool ListInsert(LinkList &L, int i, int e) {
if (i < 1)
return false;
LNode *p;
int j = 0;
p = L;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p == NULL) {
return false;
}
LNode *s = (LNode *) malloc(sizeof(LNode));
s->key = e;
s->next = p->next;
p->next = s;
return true;
}
void PrintList(LinkList L) {
LNode *p = L->next;
while (p != NULL) {
printf("%d ", p->key);
p = p->next;
}
printf("\n");
}
void ListSort(LinkList &L) {
LNode *p, *m, *q;
p = (LNode *) malloc(sizeof(LNode));
m = (LNode *) malloc(sizeof(LNode));
q = (LNode *) malloc(sizeof(LNode));
m = L->next;
while (m != NULL) {
p = m;
q = p->next;
while (q != NULL) {
int temp;
if (p->key > q->key) {
temp = p->key;
p->key = q->key;
q->key = temp;
PrintList(L);
}
q = q->next;
}
m = m->next;
}
}
int main() {
LinkList L;
InitList(L);
int arr[20] = {1, 4, 6, 8, 2, 3, 5, 7, 9, 0, 10, 11, 15, 14, 13, 12};
// int arr[20] = {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0};
for (int i = 0; i < 16; i++) {
printf("%d ", arr[i]);
}
printf("\n");
for (int i = 1; i <= 16; i++) {
ListInsert(L, i, arr[i - 1]);
}
ListSort(L);
PrintList(L);
return 0;
}
