代码地址:LeetCode/src/lianBiao/_160_相交链表.java · HuaCai/Algorithm - 码云 - 开源中国 (gitee.com)
解题思路一: 暴力穷举,时间复杂度为O(m*n),其中m、n分别为两个链表的长度
class Solution160 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
while (headA != null) {
ListNode head = headB;
while (head != null) {
if (headA == head) {
return headA;
} else {
head = head.next;
}
}
headA = headA.next;
}
return null;
}
}
解题思路二: 利用Set集合的唯一性;时间复杂度为O(m+n),其中n为headA链表的长度,空间复杂度为O(m),其中m是链表headA的长度
class Solution160 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
ListNode temp = headA;
while (temp != null) {
set.add(temp);
temp = temp.next;
}
temp = headB;
while (temp != null) {
if (set.contains(temp)) return temp;
temp = temp.next;
}
return null;
}
}
解题思路三: 二次遍历;时间复杂度为O(m+n),空间复杂度为O(1);假设headA链表较长(headB链表较长或者两个链表长度相等也同理),先计算出两个链表的长度差x,然后进行x次headA.next,然后比较相等的同时进行next操作,如果相等则返回,如果没有相等的则说明链表没有相交的部分
class Solution160 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int l1 = 0, l2 = 0, diff = 0;
ListNode a = headA, b = headB;
while (a != null) {
l1++;
a = a.next;
}
while (b != null) {
l2++;
b = b.next;
}
if (l1 > l2) {
a = headA;
b = headB;
diff = l1 - l2;
} else {
a = headB;
b = headA;
diff = l2 - l1;
}
for (int i = 0; i < diff; i++) {
a = a.next;
}
while (a != null && b != null) {
if (a == b) {
return a;
}
a = a.next;
b = b.next;
}
return null;
}
}
解题思路四: 二次遍历;时间复杂度为O(m+n),空间复杂度为O(1);指针1遍历headA,headA遍历完遍历list2,指针2遍历headB,headB遍历完遍历headA,这样就能保证指针1和指针2相遇。
class Solution160 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode a = headA, b = headB;
while (a != b) {
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
}