21. Merge Two Sorted Lists
Description
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.
Solution
考察对链表的操作,画个图一目了然。两个指针比较移动,设置一个头指针指向两个链表头结点中较小的那一个,最后返回连接后的链表即可。没有推敲很细致的操作,看了一下Runtime Distribution中最快的解法,感觉没多大区别,就不优化了。
Complexity analysis
O(n+m),n\m分别为两个链表的长度。复杂度是线性。
Code
/**
* 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* head;
if (l1 -> val > l2 -> val) {
ListNode* temp = l1;
l1 = l2;
l2 = temp;
}
head = l1;
while(l1 -> next && l2) {
if (l1 -> next -> val > l2 -> val) {
ListNode* temp = l2 -> next;
l2 -> next = l1 -> next;
l1 -> next = l2;
l2 = temp;
} else if (l1 -> next -> val <= l2 -> val) {
l1 = l1->next;
}
}
if (l1 -> next == NULL && l2 != NULL) {
l1 -> next = l2;
}
return head;
}
};
Result