21. 合并两个有序链表

题目

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例 1:

21. 合并两个有序链表_第1张图片

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]
Line 18: Char 16: runtime error: member access within address 0x7f9d912400e0 with insufficient space for an object of type 'ListNode' (solution.cpp)
0x7f9d912400e0: note: pointer points here
 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00
              ^
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:27:16

思路

新建一个链表结点p,然后同时遍历 list1 和 list2,如果 list1->val < list2->val,就将当前结点接在p后面,然后list1指针后移。

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode *head = new ListNode(-1);
        ListNode *p = head;
        while(list1 && list2){      
            if(list1->val <= list2->val){   // 
                p->next = list1;
                list1 = list1->next;
            }else{
                p->next = list2;
                list2 = list2->next;
            }
            p = p->next;
        }

        if(list1){
            p->next = list1;
        }
        if(list2){
            p->next = list2;
        }
        return head->next;        
    }
};

learn

新建结点的代码:

ListNode *head = new ListNode(-1);

你可能感兴趣的:(LeetCode,链表,数据结构)