leetcode160-相交链表
中文链接:
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
英文链接:
https://leetcode.com/problems/intersection-of-two-linked-lists/
题目详述
编写一个程序,找到两个单链表相交的起始节点。
例如,下面的两个链表:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
在节点 c1 开始相交。
注意:
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) {
int lengthA = 0;
int lengthB = 0;
ListNode tempA = headA;
ListNode tempB = headB;
while(tempA != null)
{
lengthA++;
tempA = tempA.next;
}
while(tempB != null)
{
lengthB++;
tempB = tempB.next;
}
tempA = headA;
tempB = headB;
if(lengthB > lengthA)
{
int cha = lengthB - lengthA;
for(int i=0;i<cha&&tempB != null;i++)
tempB = tempB.next;
}else{
int cha = lengthA - lengthB;
for(int i=0;i<cha&&tempA != null;i++)
tempA = tempA.next;
}
while(tempA != null && tempB != null && tempA != tempB)
{
tempA = tempA.next;
tempB = tempB.next;
}
return tempA;
}
}
代码讲解