目錄
LeetCode-21題
LeetCode-21題
將兩個升序鏈表合并成一個新的升序鏈表并返回
class Solution {public ListNode mergeTwoLists(ListNode list1, ListNode list2) {if (list1 == null)return list2;if (list2 == null)return list1;ListNode dummyHead = new ListNode();ListNode curr = dummyHead;// 雙指針ListNode p1 = list1;ListNode p2 = list2;while (p1 != null && p2 != null) {// 鏈入節點值較小的節點if (p1.val < p2.val) {curr.next = p1;p1 = p1.next;} else {curr.next = p2;p2 = p2.next;}curr = curr.next;}// 處理剩余節點if (p1 != null)curr.next = p1;if (p2 != null)curr.next = p2;return dummyHead.next;}private static class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
}