lc_top_0927

lc21 合并两个有序链表

/**
 * 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 l1, ListNode l2) {
        ListNode dummy = new ListNode();
        ListNode pre = dummy;
        while (p1 != null || p2 != null) {
            int v1 = p1 != null ? p1.val : 101;
            int v2 = p2 != null ? p2.val : 101;
            pre.next = v1 < v2 ? p1 : p2;
            if (v1 < v2) {
                pre.next = p1;
                p1 = p1.next;
            } else {
                pre.next = p2;
                p2 = p2.next;
            }
            pre = pre.next;
        }
        return dummy.next;
    }
}

合理使用dummy节点;

posted @ 2022-09-27 22:16  北de窗  阅读(25)  评论(0)    收藏  举报