You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = [] Output: []
Example 3:
Input: list1 = [], list2 = [0] Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
- Both
list1
andlist2
are sorted in non-decreasing order.
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode header1 = new ListNode(0); header1.next = l1; ListNode header2 = new ListNode(0); header2.next = l2; ListNode header3 = new ListNode(0); ListNode tail = header3; ListNode tmp; while(header1.next!=null && header2.next!=null){ if(header1.next.val <= header2.next.val){ // detach first in list 1 tmp = header1.next; header1.next = header1.next.next; }else{ // detach first in list 1 tmp = header2.next; header2.next = header2.next.next; } tail.next = tmp; tail = tail.next; } if(header1.next != null){ tail.next = header1.next; }else{ tail.next = header2.next; } return header3.next; } }------------------------3 rd Pass ----------------list1 和list 2 是不需要header的-------- 思路和 第二遍 一样
/*** 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 header;ListNode* tail = &header;while (list1 || list2) {if (list1 == nullptr || (list2 && list1->val > list2->val)) {tail->next = list2;list2 = list2->next;tail = tail->next;} else {tail->next = list1;list1 = list1->next;tail = tail->next;}}return header.next;}};
Error :
Still need to check list2 is null or not.
Since we cannot make sure it is not null
No comments:
Post a Comment