题目:
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
图示两个链表在节点 c1 开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构 。
原题OJ链接https://leetcode.cn/problems/intersection-of-two-linked-lists/description/
解答:
/**
* 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 lenA = length(headA);
int lenB = length(headB);
int len = lenA -lenB;
ListNode pl = new ListNode();
ListNode ps = new ListNode();
if(len >= 0){
pl = headA;
ps = headB;
}
else{
len = lenB -lenA;
ps = headA;
pl = headB;
}
if(pl == null || ps == null){
return null;
}
while(len>0){
pl = pl.next;
len--;
}
while(pl != ps){
pl = pl.next;
ps = ps.next;
}
return pl;
}
public static int length(ListNode head){
ListNode cur = head;
int length = 0;
while(cur != null){
cur = cur.next;
length++;
}
return length;
}
}