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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值