Files
leetcode/21.merge-two-sorted-lists.java
2025-05-17 17:06:34 +08:00

60 lines
1.6 KiB
Java

/*
* @lc app=leetcode id=21 lang=java
*
* [21] Merge Two Sorted Lists
*/
// @lc code=start
/**
* 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) {
if(list1 == null || list2 == null) {
return list1 == null?list2:list1;
}
ListNode h = null, cur = null;
while(list1 != null && list2!=null) {
if(list1.val <= list2.val) {
if(h == null) {
h = cur = list1;
list1 = list1.next;
h.next = null;
} else {
cur.next = list1;
list1 = list1.next;
cur = cur.next;
cur.next = null;
}
} else {
if(h == null) {
h = cur = list2;
list2 = list2.next;
h.next = null;
} else {
cur.next = list2;
list2 = list2.next;
cur = cur.next;
cur.next = null;
}
}
}
if (list1 !=null) {
cur.next = list1;
}
if(list2 != null) {
cur.next = list2;
}
return h;
}
}
// @lc code=end