leetcode(21): Merge Two Sorted Lists
题目
翻译:
合并2个已经排序的链表,并且返回一个新的链表。这个新的链表应该由前面提到的2个链表的节点所组成。
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
思路
解法还是很简单的,但是需要注意以下几点:
-
如果两个链表都空,则返回null;
-
如果链表1空,则返回链表2的头节点;反之,如果链表2为空,则返回链表1的头节点;
-
两个链表都不空的情况下:
比较两个链表的头节点的值,哪个小,则新链表的头节点为哪个;
举例:l1: 1->3->5; l2:2->4->6->7;则:head = l1的头节点,此时head.next = l1.next 或者 l2
代码
/**
* 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;
else if(l2 == NULL)
return l1;
ListNode *Result;
if((l1->val)<(l2->val))
{ Result = l1;
Result->next =mergeTwoLists(l1->next,l2);
return Result;
}
else
{
Result = l2;
Result->next =mergeTwoLists(l1,l2->next);
return Result;
}
}
};