两个链表都不空的时候比较节点,有一个空时就指向另一个非空
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0),cur= head;
while(l1!=null && l2!=null){
if(l1.val >= l2.val){
cur.next = l2;
l2 = l2.next;
}else{
cur.next = l1;
l1 = l1.next;
}
cur = cur.next;
}
cur.next = l1 ==null ? l2:l1;
return head.next;
}
}
Krahets 大佬的思路
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a=headA,b=headB;
while(a!=b){
a = a!=null ? a.next : headB;
b = b!=null ? b.next : headA;
}
return a;
}
}
|