LeetCode-相交链表(160)
题目描述:
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
图示两个链表在节点 c1 开始相交:
题目数据保证整个链式结构中不存在环。
注意,函数返回结果后,链表必须保持其原始结构 。
思路: 首先使用两个循环求得两个链表的长度,然后相减得到差值,指向长的链表的指针移动差值步,然后和短链表指针同时移动,这里是使用循环实现,当长短指针相等时就到达了相交节点。当然实现代码时要注意长短链表指针是否为空的问题,长短链表指针同时移动的循环中要注意长短链表的指针都不可为空,如果为空则跳出并且经过判断,确定两个链表直到遍历完都没有相交的节点,返回null。如果是因为长短链表指针相等而跳出的就跳出相应的相交节点。
代码:
public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {int lenA = 0, lenB = 0;ListNode curA = headA;ListNode curB = headB;while (curA != null) {curA = curA.next;lenA++;}while (curB != null) {curB = curB.next;lenB++;}int len = lenA - lenB;ListNode listL = headA;ListNode listS = headB;if (len < 0) {len = lenB - lenA;listL = headB;listS = headA;}while (len != 0) {listL = listL.next;len--;}while (listS != null && listL != null && listL != listS) {listL = listL.next;listS = listS.next;}if (listL == listS && listL == null) {return null;}return listL;}
}