• 2.10

    • 依旧懒得做
  • 1.24

    • 懒得做
  • 1.18

    • 秒了
  • 11月9日

  • 后面错误点:

    1. 不用声明新指针,用前面的指针再指向head就行
    2. 到达同一个位置后,一起往后走,并非之前想的第一个节点就是相交点
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode temp1 = headA;
        ListNode temp2 = headB;
 
        if(temp1==null||temp2==null){
            return null;
        }
        int lengthA=0;
        int lengthB=0;
        while(temp1!=null){
            lengthA++;
            temp1=temp1.next;
        }
        while(temp2!=null){
            lengthB++;
            temp2=temp2.next;
        }
        ListNode temp11 = headA;
        ListNode temp22 = headB;
 
        if(lengthA>lengthB){
            for(int i=0;i<lengthA-lengthB;i++){
            temp11=temp11.next;
            }
        }else if(lengthA<lengthB){
            for(int i=0;i<lengthB-lengthA;i++){
              temp22 = temp22.next;
            }
        }
        while(temp11!=null){
            if(temp11==temp22){
                return temp11;
            }else{
                temp11=temp11.next;
                temp22=temp22.next;
            }
        }
        return null;
        
    }
}
  • 先判空
  • 再对其
  • 最后相等就相等
/**
 * 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;
 
        int lengthA = 0;
        int lengthB = 0;
 
        ListNode l1 = headA;
        ListNode l2 = headB;
 
        while(l1!=null){
            lengthA++;
            l1 = l1.next;
        }
        while(l2!=null){
            lengthB++;
            l2 = l2.next;
        }
        
        if(lengthA<=lengthB){
            for(int i=0;i<lengthB-lengthA;i++){
                headB = headB.next;
            }
        }else{
            for(int i=0;i<lengthA-lengthB;i++){
                headA = headA.next;
            }
        }
        while(headA!=null){
            if(headA==headB){
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
}