合並兩個升序鏈表,要點在於:邊界條件判斷,即鏈表可能為空。 剩下的 /* 1: 邊界條件判斷 2: 頭結點的值 3: */ Node * mergeOrderedLinkedList(Node *head1, Node *head2) { //邊界條件判斷 if(null == head1) return head2; if(null == head2) return head1; Node *head = null, *p1 = null, *p2 = null; //獲取頭結點 if(head1->value < head2->value) { head = head1; p1 = head1->next; p2 = head2; } else { head = head2; p2 = head2->next; p1 = head1; } //依次合並 Node *p3 = head; while(null != p1 && null != p2) { if(p1->value < p2->value) { p3->next = p1; p3 = p1; p1 = p1->next; } else { p3->next = p2; p3 = p2; p2 = p2->next; } } if(null == p1) { p3->next = p2; } else{ p3->next = p1; } return head; } (2)遞歸實現。 按照上面的算法實現,思路很清晰簡單,但是代碼太長。可以知道每次循環的動作都是相似的,用遞歸應該可以實現。如下 [cpp] Node * mergeOrderedLinkedListRecursive(Node *head1, Node *head2) { //邊界條件判斷 if(null == head1) return head2; if(null == head2) return head1; Node *head = null; www.2cto.com if(head1->value < head2->value) { head = head1; head->next = mergeOrderedLinkedListRecursive(head1->next, head2); } else { head = head2; head->next = mergeOrderedLinkedListRecursive(head1, head2->next); } return head; }