/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}else if(l2 == null){
return l1;
}
ListNode head = l1;
if(l1.val > l2.val){
head = l2;
l2 = l2.next;
}else{
l1 = l1.next;
}
ListNode cur = head;
while(l1!=null&&l2!=null){
if(l1.val <= l2.val){
cur.next = l1;
l1 = l1.next;
}else{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if(l1 != null){
cur.next = l1;
}else if(l2 != null){
cur.next = l2;
}
return head;
}
}
设置dum结点,dum.next指向头结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dum = new ListNode(0),cur = dum;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
cur.next = l1;
l1 = l1.next;
}else{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1!=null?l1:l2;
return dum.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null||headB == null){return null;}
ListNode l1 = headA,l2 = headB;
while(l1 != l2){
if(l1 == null){l1 = headB;}
else{l1 = l1.next;}
if(l2 == null){l2 = headA;}
else{l2 = l2.next;}
}
return l1;
}
}