leetcode刷题系列----模式2(Datastructure 链表)- 160:Intersection of Two Linked List 相交链表
Tips
- 更多题解请见本系列目录
- 此链表问题可以使用双指针解决,注意算法的复杂度为O(m+n),意味着2*(m+n)次遍历也属于该时间复杂度,不可狭隘的认为仅仅遍历m+n次链表节点。
- 双指针确实是一个很大的算法思想类。
Python
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
pointA = headA
pointB = headB
if not pointA or not pointB: return None
while pointA != pointB:
if pointA: pointA = pointA.next
else: pointA = headB
if pointB: pointB = pointB.next
else: pointB = headA
return pointA
C++
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* pointA = headA;
ListNode* pointB = headB;
if (pointA==nullptr || pointB==nullptr) return nullptr;
while (pointA!=pointB)
{
if(pointA!=nullptr) pointA=pointA->next;
else pointA=headB;
if(pointB!=nullptr) pointB=pointB->next;
else pointB=headA;
}
return pointA;
}
};
C#
public class Solution {
public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
ListNode pointA = headA;
ListNode pointB = headB;
if (pointA==null || pointB==null) return null;
while (pointA!=pointB)
{
if(pointA!=null) pointA=pointA.next;
else pointA=headB;
if(pointB!=null) pointB=pointB.next;
else pointB=headA;
}
return pointA;
}
}
Java
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pointA = headA;
ListNode pointB = headB;
if (pointA==null || pointB==null) return null;
while (pointA!=pointB)
{
if(pointA!=null) pointA=pointA.next;
else pointA=headB;
if(pointB!=null) pointB=pointB.next;
else pointB=headA;
}
return pointA;
}
}