起因今天利用空餘時間在九度做ACM的時候,需要對單鏈表進行排序,由於單鏈表不是隨機存取結構,所以我不建議用快速排序,因此採用了冒泡排序!帶前端節點的尾插法構建單鏈表
//初始化帶前端節點的鏈表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;}}
九度ACM遍曆鏈表
-
題目描述:
-
建立一個升序鏈表並遍曆輸出。
-
輸入:
-
輸入的每個案例中第一行包括1個整數:n(1<=n<=1000),接下來的一行包括n個整數。
-
輸出:
-
可能有多組測試資料,對於每組資料,
將n個整數建立升序鏈表,之後遍曆鏈表並輸出。
-
範例輸入:
-
43 5 7 9
-
範例輸出:
-
3 5 7 9
AC代碼:
#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;}}