/**
* 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-21:合并两个有序链表(Java语言实现)
最新推荐文章于 2024-08-17 15:37:21 发布