首页 > 其他分享 >O(1)空间复杂度找到相交链表的交点

O(1)空间复杂度找到相交链表的交点

时间:2022-12-12 19:35:31浏览次数:67  
标签:ListNode 复杂度 交点 fast next 链表 ans poi NULL


  相交链表

编写一个程序,找到两个单链表相交的起始节点。

如下面的两个链表

O(1)空间复杂度找到相交链表的交点_快慢指针

在节点 c1 开始相交。

解题思路:

首先将一条链首尾连起来,这时候就变成了找环的入口点的问题。我们可以用快慢指针先判断有没有环,然后再用快慢指针的交点poi开始和链表头开始找,找到的交点即为环的入口点。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == NULL || headB == NULL)return NULL;
ListNode * poi = headA;
while(poi->next){
poi=poi->next;
}
ListNode * tmp = poi;
poi->next = headA;
ListNode *fast;
ListNode *slow;
fast=slow=headB;
int cnt = 1;
while(cnt || fast!=slow){
cnt = 0;
if(fast->next == NULL || fast->next->next == NULL){tmp->next = NULL;return NULL;}
fast=fast->next->next;
slow = slow->next;
}
poi=headB;
ListNode *ans = fast;
while(poi!=ans){
poi=poi->next,ans=ans->next;
}
tmp->next = NULL;
return ans;
}
};

 

标签:ListNode,复杂度,交点,fast,next,链表,ans,poi,NULL
From: https://blog.51cto.com/u_15910522/5931537

相关文章