题目:已知两个链表head1 和head2 各自有序,请把它们合并成一个链表依然有序
分析:两个链表都应该是增序或者降序
方法一使用递归的方法
- struct Node
- {
- Node* next;
- int value;
- };
- Node* Merge(Node* head1, Node* head2)
- {
- Node* res;
- if(head1 == NULL) return head2;
- if(head2 == NULL) return head1;
- if(head1->value < head2->value)
- {
- res = head1;
- res->next = Merge(head1->next, head2);
- }
- else
- {
- res = head2;
- res->next = Merge(head1, head2->next);
- }
- return res;
- }
方法二非递归
- Node* Merge2(Node* head1, Node* head2)
- {
- Node* res,*ret;
- if(head1 == NULL) return head2;
- if(head2 == NULL) return head1;
- Node* p = head1;
- Node* q = head2;
- if(p->value < q->value)
- {
- res = p;
- p = p->next;
- }
- else
- {
- res = q;
- q = q->next;
- }
- ret = res;
- while(p && q)
- {
- if(p->value < q->value)
- {
- res->next = p;
- res = p;
- p = p->next;
- }
- else
- {
- res->next = q;
- res = q;
- q = q->next;
- }
- }
- while(p)
- {
- res->next = p;
- res = p;
- p = p->next;
- }
- while(q)
- {
- res->next = q;
- res = q;
- q = q->next;
- }
- return ret;
- }