【简单】21-合并两个有序链表 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.
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
解法
方法:归并
解法
由于两个链表都是有序的,所以两个链表头部之间更小的一个就是所有数据中最小的值,依次把两个链表头部较小的一个节点拿出来,最后就可以得到一个有序序列
代码
/**
* 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 head(0);
ListNode *curr = &head;
while(l1 != NULL || l2 != NULL){
if(l1 == NULL) {curr->next = l2; return head.next;}
if(l2 == NULL) {curr->next = l1; return head.next;}
if(l1->val < l2->val){
curr->next = l1;
curr = curr->next;
l1 = l1->next;
}
else{
curr->next = l2;
curr = curr->next;
l2 = l2->next;
}
}
return head.next;
}
};
Email:1252418308@qq.com