2025-05-17提交

This commit is contained in:
asahi
2025-05-17 17:01:56 +08:00
parent c4e1e74677
commit a62543b3fd
7 changed files with 454 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
/*
* @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