LeetCode 160. Intersection of Two Linked Lists 题解 —— Java

题目链接:https://leetcode.com/problems/intersection-of-two-linked-lists/#/description

题目要求:找出两个链表的交叉点,若两链表没有交叉点,返回null。

思路:(1)首先遍历两个链表,计算出两个链表的长度   O(N)

(2)对于较长的那个链表,让该链表的指针先走几步——所走的步数为两链表的长度差

(3)再让两链表的指针每次走一步,若两指针相遇了,那么首次相遇的节点即为两链表的交叉节点;若不相遇,则两个链表不存在交叉点。


Java代码如下:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lengthA = 0;
        int lengthB = 0;
        ListNode current = headA;
        // 计算出链表A和B的长度
        while(current != null){
        	lengthA ++;
        	current = current.next;
        }
        current = headB;
        while(current != null){
        	lengthB ++;
        	current = current.next;
        }
        int sub = Math.abs(lengthB - lengthA);
        ListNode first = headA;
        ListNode second = headB;
        // 链表较长的那个对应的指针先走几步——先走的步数为两个链表的长度差
        if(lengthB > lengthA){
        	for(int i = 0; i<sub; i++){
        		second = second.next;
        	}
        } else {
        	for(int i = 0; i<sub; i++){
        		first = first.next;
        	}
        }
        while(first!=null && second != null){
        	// 当两个指针首次相遇时,即为两个链表的交叉点
        	if(first==second){
        		return first;
        	} else {
        		first = first.next;
        		second = second.next;
        	}
        }
        return null;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章