n个记录存储在带头结点的双向链表中,利用双向冒泡排序对其进行升序排序。
输入样例:
5
1 2 3 4 5
5
5 4 3 2 1
5
2 3 4 5 1
5
5 1 2 3 4
5
1 4 3 2 5
输出样例:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode {
int data;
struct LNode *prior, *next;
} LNode, *LinkList;
void ListInit(LinkList *head);
void ListTailInsert(LinkList head, int e);
void ListDestroy(LinkList *head);
void ListShow(LinkList head);
void ListBubbleSort(LinkList head);
int main() {
int m, x;
while (scanf("%d", &m) && m != 0) {
LinkList L = NULL;
ListInit(&L);
while (m--) {
scanf("%d", &x);
ListTailInsert(L, x);
}
ListBubbleSort(L);
ListShow(L);
ListDestroy(&L);
}
return 0;
}
void ListInit(LinkList *head) {
*head = (LNode *) calloc(1, sizeof(LNode));
(*head)->prior = (*head)->next = NULL;
}
void ListTailInsert(LinkList head, int e) {
LNode *newNode = (LNode *) malloc(sizeof(LNode));
LNode *tail = head;
while (tail->next) tail = tail->next;
newNode->data = e;
newNode->next = NULL;
newNode->prior = tail;
tail->next = newNode;
}
void ListDestroy(LinkList *head) {
LNode *tmp;
while (*head) {
tmp = *head;
*head = (*head)->next;
free(tmp);
}
}
void ListShow(LinkList head) {
for (LNode *cursor = head->next; cursor; cursor = cursor->next) {
printf("%d%c", cursor->data, (cursor->next) ? 32 : 10);
}
}
void ListBubbleSort(LinkList head) {
LNode *lBorder, *rBorder;
LNode *tail = head;
/*init lBorder and rBorder*/
lBorder = head;//lBorder->next is the first data
while (tail->next) tail = tail->next;
tail->next = (LNode *) calloc(1, sizeof(LNode));
tail->next->prior = tail;
tail = tail->next;
rBorder = tail;//rBorder->prior is the last data
/*sort*/
while (lBorder->next != rBorder) {
LNode *cur = lBorder->next;
/*from left to right*/
while (cur->next != rBorder) {
if (cur->data > cur->next->data) {
LNode *tmp = cur->prior;
/*swap*/
tmp->next = tmp->next->next;
cur->next = cur->next->next;
tmp->next->next = cur;
cur->next->prior = cur;
tmp->next->prior = tmp;
cur->prior = tmp->next;
} else {
cur = cur->next;
}
}
rBorder = rBorder->prior;
if (lBorder->next == rBorder) break;
/*from right to left*/
while (cur->prior != lBorder) {
if (cur->data < cur->prior->data) {
LNode *tmp = cur->next;
/*swap*/
tmp->prior = tmp->prior->prior;
cur->prior = cur->prior->prior;
tmp->prior->prior = cur;
cur->prior->next = cur;
tmp->prior->next = tmp;
cur->next = tmp->prior;
} else {
cur = cur->prior;
}
}
lBorder = lBorder->next;
}
tail->prior->next = NULL;
free(tail);//tail become a dangling pointer
}