leetcode地址: leetcode.cn/problems/in…
原题描述:
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
进阶:时间复杂度o(n) 空间复杂度o(1)
解题思路:
方法1:
空间换时间,遍历链表A,把链表A的节点放入HashMap,再遍历链表B,每次执行都去HashMap查找一次,如果能找到说明是,如果找不到说明没有。
空间复杂度o(n) 时间复杂度 (onlogn);
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
HashMap<ListNode,Boolean> map = new HashMap<>();
while(headA!=null){
map.put(headA,Boolean.TRUE);
headA = headA.next;
}
while(headB!=null){
Boolean aBoolean = map.get(headB);
if(aBoolean!=null && aBoolean){
return headB;
}
headB = headB.next;
}
return null;
}
}
执行,一次通过。
方法2:
如果两个链表相交,那么他们的最后一个节点一定相同,在遍历的过程中记录他们的长度,这样也能获得长度差,让长的链表先走长度差的距离,然后循环让双指针向后移动,相等则说明到达入口。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int length1 = 0;
int length2 = 0;
ListNode tempA = headA;
ListNode tempB = headB;
while (tempA != null) {
length1++;
tempA = tempA.next;
}
while (tempB != null) {
length2++;
tempB = tempB.next;
}
if (tempA != tempB) {
return null;
}
int count = length1 - length2;
if (count > 0) {
for (int i = 0; i < count; i++) {
headA = headA.next;
}
} else if (count < 0) {
count = -count;
for (int i = 0; i < count; i++) {
headB = headB.next;
}
}
while (headA != null) {
if (headA == headB) {
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
}