Home LeetCode. 21. Merge Two Sorted Lists
Post
Cancel

LeetCode. 21. Merge Two Sorted Lists

image

[Link] https://leetcode.com/problems/merge-two-sorted-lists/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode nullNode = new ListNode();
        ListNode curNode = nullNode;
        ListNode node1 = list1, node2 = list2;
        while(node1 != null && node2 != null) {
          if(node1.val < node2.val) {
            curNode.next = node1;
            curNode = node1;
            node1 = node1.next;
            if(node1 == null) break;
          } else {
            curNode.next = node2;
            curNode = node2;
            node2 = node2.next;
            if(node2 == null) break;
          }
        }
        if(node1 == null && node2 != null) curNode.next = node2;
        else if(node1 != null && node2 == null) curNode.next = node1;
        return nullNode.next;
    }
}
This post is licensed under CC BY 4.0 by the author.