//初始化带头节点的链表 struct lnode *head, *s, *r, *p; head = malloc(sizeof(struct lnode)); r = head; for(i = 0; i < n; i ++) { scanf("%d", &d); s = malloc(sizeof(struct lnode)); s -> data = d; r -> next = s; r = s; } r -> next = NULL;
/** * Description:单链表的冒泡排序 */ void BubbleSort(struct lnode *head) { struct lnode *f, *p, *x, *y; f = NULL; //判断是否只有一个元素或者没有元素 if(head -> next == NULL || head -> next -> next == NULL) { return; } while(f != head->next->next) { //外层是N - 1次循环,升序 for(p = head; p -> next -> next != f; p = p -> next) { if(p -> next -> data > p -> next -> next ->data) { x = p -> next; y = p -> next -> next; p -> next = y; x -> next = y -> next; y -> next = x; } } f = p -> next; } }
建立一个升序链表并遍历输出。
输入的每个案例中第一行包括1个整数:n(1<=n<=1000),接下来的一行包括n个整数。
可能有多组测试数据,对于每组数据,
将n个整数建立升序链表,之后遍历链表并输出。
4 3 5 7 9
3 5 7 9
#include <stdio.h> #include <stdlib.h> #include <string.h> struct lnode { int data; struct lnode *next; }; void BubbleSort(struct lnode * head); int main() { int n, i, d; while(scanf("%d", &n) != EOF) { //初始化带头节点的链表 struct lnode *head, *s, *r, *p; head = malloc(sizeof(struct lnode)); r = head; for(i = 0; i < n; i ++) { scanf("%d", &d); s = malloc(sizeof(struct lnode)); s -> data = d; r -> next = s; r = s; } r -> next = NULL; //冒泡排序 BubbleSort(head); //打印输出 for(p = head -> next; p != NULL; p = p -> next) { if(p -> next == NULL) { printf("%d\n", p -> data); }else { printf("%d ", p -> data); } } } return 0; } /** * Description:单链表的冒泡排序 */ void BubbleSort(struct lnode *head) { struct lnode *f, *p, *x, *y; f = NULL; //判断是否只有一个元素或者没有元素 if(head -> next == NULL || head -> next -> next == NULL) { return; } while(f != head->next->next) { for(p = head; p -> next -> next != f; p = p -> next) { if(p -> next -> data > p -> next -> next ->data) { x = p -> next; y = p -> next -> next; p -> next = y; x -> next = y -> next; y -> next = x; } } f = p -> next; } }