LeetCode-21:合并两个有序链表(Java语言实现)

/**
 * 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 p1, ListNode p2) {
        ListNode p3 = new ListNode(-1, null);
        ListNode p4 = p3;
        while (p1 != null && p2 != null) {

            if (p1.val < p2.val) {
                p3.next = new ListNode(p1.val, null);
                p1 = p1.next;
                p3 = p3.next;
            } else {
                p3.next = new ListNode(p2.val, null);
                p2 = p2.next;
                p3 = p3.next;
            }

        }
        if (p1 == null) {
            p3.next = p2;
        }
        if (p2 == null) {
            p3.next = p1;
        }
        return p4.next;
    }
}

你可能感兴趣的:(leetcode,链表,java,数据结构,算法)