您的位置:首页 > 编程语言 > Java开发

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

2017-03-20 21:10 405 查看
题目链接: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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: