1、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.
/**
* 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 dummy(INT_MIN);
ListNode* temp=&dummy;
while(l1&&l2){
if(l1->val<l2->val){
temp->next=l1;
l1=l1->next;
}
else{
temp->next=l2;
l2=l2->next;
}
temp=temp->next;
}
temp->next = l1 ? l1 : l2;
return dummy.next;
}
};
既然是sorted list,则不用担心每个list的顺序了,只需要不停的比较两个list对应的val的大小。最初设一个无穷小的节点,选择与第一个元素较小的list相连,分别指向他们的next,temp指向的节点继续担任最小节点的角色,选择下一对中较小的节点,直到有一方为空,则选择剩余一个节点作为temp的next.