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节点;
标签:p2,pre,p1,ListNode,lc,val,0927,top,next From: https://www.cnblogs.com/beichuang/p/16736220.html