單鏈表的冒泡排序

來源:互聯網
上載者:User
起因今天利用空餘時間在九度做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;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.