LeetCode——Intersection of Two Linked Lists

时间:2021-07-16 08:37:42

Description:

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3

begin to intersect at node c1.

求两个链表的相交的部分

/**
* 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) {
if(headA==null || headB==null)
return null;
ListNode aNode = headA;
ListNode bNode = headB;
int aLen = 0, bLen = 0;
while(aNode != null) {
aLen ++;
aNode = aNode.next;
}
while(bNode != null) {
bLen ++;
bNode = bNode.next;
}
if(aNode != bNode)
return null;
if(aLen > bLen) {
for(int i = 0; i < aLen-bLen; i++)
headA = headA.next;
}
else if(aLen < bLen) {
for(int i=0; i<bLen-aLen; i++)
headB = headB.next;
}
while(headA != headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
}