160. 相交链表

160. 相交链表

考研那段时间记得太牢了。
当然也是简单题。。

/**
 * 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) {
        int lengthA = getLength(headA), lengthB = getLength(headB);
        int step = Math.abs(lengthA-lengthB);
        if(lengthA > lengthB){
            headA = forward(headA, step);
        }
        else{
            headB = forward(headB, step);
        }
        while(headA!=null && headB != null){
            if(headA == headB)
                return headA;
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
    public int getLength(ListNode head){
        int length = 0;
        ListNode p = head;
        while(p!=null){
            p = p.next;
            length ++;
        }
        return length;
    }
    public ListNode forward(ListNode head, int step){
        while(step>0){
            head = head.next;
            step --;
        }
        return head;
    }
}

你可能感兴趣的:(力扣Hot100,链表,数据结构)