文章目錄
題目已知兩個有序鏈表,試合并這兩個鏈表,使得合并後的鏈表仍然有序(註:這兩個鏈表沒有公用結點,即不交叉)。分析既然兩個鏈表都是有序的,所以合并它們跟合并兩個有序數組沒有多少區別,只是鏈表操作涉及到指標,不能大意。方法一:非遞迴方法使用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);}