LeetCode 160. 相交链表
题目:给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
进阶:你能否设计一个时间复杂度 O(m + n) 、仅用 O(1) 内存的解决方案?
链接 https://leetcode.cn/problems/intersection-of-two-linked-lists/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
nodeList = []
while headA:
nodeList.append(headA)
headA = headA.next
while headB:
if headB in nodeList:
return headB
headB = headB.next
return None

但非常耗时,至于进阶问题,个人觉得应该用双指针,但没想到具体该怎么做
复杂度分析
时间复杂度:O(m+n),其中 m 和 n 是分别是链表 headA 和 headB 的长度。需要遍历两个链表各一次。
空间复杂度:O(m),其中 m 是链表 headA 的长度。需要使用哈希集合存储链表 headA 中的全部节点。


# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if headA == None or headB == None:
return None
pA,pB = headA,headB
while pA != pB:
pA = pA.next if pA != None else headB
pB = pB.next if pB != None else headA
return pA
速度快很多
复杂度分析
时间复杂度:O(m+n),其中 m 和 n 是分别是链表 headA 和 headB 的长度。两个指针同时遍历两个链表,每个指针遍历两个链表各一次。
空间复杂度:O(1)。
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode-solutio-a8jn/
先让两个链表剩余长度相同,然后同步遍历,也是空间 O(1)
好秀,我好像也灵光闪现过这一思路,但觉得要先算出长度就放弃了
class Solution {
public:
int getLength(ListNode* head) {
int ans = 0;
for (;head;head = head->next) ++ans;
return ans;
}
ListNode *getIntersectionNode(ListNode* headA, ListNode* headB) {
int lenA = getLength(headA);
int lenB = getLength(headB);
int len = 0;
if (lenA > lenB) {
len = lenB;
while (lenA-- > lenB)
headA = headA->next;
} else {
len = lenA;
while (lenB-- > lenA)
headB = headB->next;
}
while (len--) {
if (headA == headB)
return headA;
headA = headA->next;
headB = headB->next;
}
return nullptr;
}
};