Java现有两个递增的链表La,Lb,单个链表的长度都为n,请将这两个链表合并成一个新链表Lc,新链表Lc中的节点仍然是递增排序的。java
时间: 2024-03-13 18:26:25 浏览: 97
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode merge(ListNode La, ListNode Lb) {
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (La != null && Lb != null) {
if (La.val < Lb.val) {
curr.next = La;
La = La.next;
} else {
curr.next = Lb;
Lb = Lb.next;
}
curr = curr.next;
}
if (La != null) {
curr.next = La;
}
if (Lb != null) {
curr.next = Lb;
}
return dummy.next;
}
阅读全文