鏈表合并演算法

來源:互聯網
上載者:User
文章目錄
  • 方法一:非遞迴方法
題目已知兩個有序鏈表,試合并這兩個鏈表,使得合并後的鏈表仍然有序(註:這兩個鏈表沒有公用結點,即不交叉)。分析既然兩個鏈表都是有序的,所以合并它們跟合并兩個有序數組沒有多少區別,只是鏈表操作涉及到指標,不能大意。方法一:非遞迴方法使用2個指標list1和list2分別遍曆兩個鏈表,將較小值結點歸併到結果鏈表中。如果有一個鏈表歸併結束後另一個鏈表還有結點,則把另一個鏈表剩下部分加入到結果鏈表的尾部。代碼如下所示:
struct node *sorted_merge(struct node *a, struct node *b) {    struct node result; //使用一個結點用於儲存結果    struct node *tail = &result;     if (a == NULL)  return b; //特殊情況處理    else if (b == NULL) return a;    while (a && b) {        if (a->data <= b->data) { //a鏈表結點值小,加入到鏈表尾部,並更新tail,遍曆a鏈表下一個結點            tail->next = a;            tail = a;            a = a->next;        } else {     //b鏈表結點值小,加入到鏈表尾部,更新tail,遍曆b鏈表下一個結點            tail->next = b;            tail = b;            b = b->next;        }    }    if (a)  //a結點未遍曆完,則加入到尾部        tail->next = a;    if (b)  //b結點未遍曆完,加入到尾部        tail->next = b;    return result.next;}

方法二:遞迴演算法

struct node* sorted_merge_recur(struct node* a, struct node* b){    struct node* result = NULL;    //基礎情況    if (a==NULL) return(b);    else if (b==NULL) return(a);    // 遞迴遍曆    if (a->data <= b->data) {        result = a;        result->next = sorted_merge_recur(a->next, b);    }    else {        result = b;        result->next = sorted_merge_recur(a, b->next);    }    return(result);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.