链表的结构:
struct ListNode{
int data;
struct ListNode* next;
};
迭代版本实现:
ListNode* mergeTwoLists_iter(ListNode* l1, ListNode*l2){
ListNode* head=NULL;
ListNode* p = NULL;
ListNode* p1=l1;
ListNode* p2=l2;
if (p1 == NULL&&p2 == NULL) return NULL;
while (p1 != NULL&&p2 != NULL){
if (p1->data < p2->data){
if (head == NULL){
head = p1;
p = head;
}
else{
p->next = p1;
p = p->next;
}
p1 = p1->next;
}
else{
if (head == NULL){
head = p2;
p = head;
}
else{
p->next = p2;
p = p->next;
}
p2 = p2->next;
}
}
if (p1 == NULL&&p2 != NULL){
if (head == NULL){
head = p2;
p = head;
}
else{
p->next = p2;
p = p->next;
}
p2 = p2->next;
}
if (p1 != NULL&&p2 == NULL){
if (head == NULL){
head = p1;
p = head;
}
else{
p->next = p1;
p = p->next;
}
p1 = p1->next;
}
return head;
}
递归版本实现:
ListNode* mergeTwoLists_recur(ListNode* l1, ListNode* l2){
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode* head = NULL;
if (l1->data < l2->data){
head = l1;
head->next = mergeTwoLists_recur(l1->next, l2);
}else{
head = l2;
head->next = mergeTwoLists_recur(l1, l2->next);
}
return head;
}
注意理解递归和迭代版本的思想啦,尤其针对递归部分需要认真理解!
PS:刚才我们处理的是合并两个排好序的链表,如果将2个链表换成多个链表呢?
ListNode* merge_multi_lists(vector<ListNode*>& vec){
int len = vec.size();
if (len == 0) return NULL;
if (len == 1) return vec[0];
ListNode* ret = merge(vec, 0, len);
return ret;
}
ListNode* merge(vector<ListNode*>& vec_list, int i, int j){
if (i == j) return vec_list[i];
ListNode* ret = NULL;
if (i < j){
int mid = (i + j) / 2;
ListNode* lhs = merge(vec_list, i, mid);
ListNode* rhs = merge(vec_list, mid + 1, j);
ret = mergeTwoLists_recur(lhs, rhs);
}
return ret;
}
ListNode* mergeTwoLists_recur(ListNode* l1, ListNode* l2){
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode* head = NULL;
if (l1->data < l2->data){
head = l1;
head->next = mergeTwoLists_recur(l1->next, l2);
}else{
head = l2;
head->next = mergeTwoLists_recur(l1, l2->next);
}
return head;
}