leetcode 题解Merge Two Sorted Lists(有序链表归并)

时间:2023-03-09 22:16:55
leetcode 题解Merge Two Sorted Lists(有序链表归并)

题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

说明:有序链表归并(从小到大)

1)此链表无头节点

实现:

方法一:非递归

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *la=l1,*lb=l2;
ListNode *q=NULL,*p=NULL;
if(la==NULL) return l2;
if(lb==NULL) return l1;
//此单链表无头结点,若有头结点,可直接p=head节点即可,无需下面的if...else...
if((la->val) < (lb->val))
{
p=la;
la=la->next;
}
else
{
p=lb;
lb=lb->next;
}
q=p;
while(la&&lb)
{
if((la->val) < (lb->val))
{
p->next=la;
p=la;
la=la->next;
}
else
{
p->next=lb;
p=lb;
lb=lb->next;
}
}
p->next=la?la:lb;
return q;
}
};

方法二:递归(紫红的泪大牛的代码,博客链接:http://www.cnblogs.com/codingmylife/archive/2012/09/27/2705286.html

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1; ListNode *ret = NULL; if (l1->val < l2->val)
{
ret = l1;
ret->next = mergeTwoLists(l1->next, l2);
}
else
{
ret = l2;
ret->next = mergeTwoLists(l1, l2->next);
} return ret;
}
};