/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head || !head->next) return NULL;
ListNode *slow=head,*fast=head,*flag=head;
while(true){
slow=slow->next;
fast=fast->next;
if(!fast){return NULL;}
fast=fast->next;
if(!fast){return NULL;}
if(slow==fast){break;}
}
while(true){
if(slow==flag){return slow;}
slow=slow->next;
flag=flag->next;
if(!flag){return NULL;}
}
}
};
**
每次移动都需要考虑 链表是否越界了
c++的是NULL和true
**
单链表的中点也可以用快慢指针解决
160. 相交链表
**(用额外的空间)哈希集合存储相交的节点
set的count()只返回0/1 就是出现或没出 因为没有重复元素
erase(iterator) ,删除定位器iterator指向的值
erase(first,second),删除定位器first和second之间的值
erase(key_value),删除键值key_value的值
find() ,返回给定值值得定位器,如果没找到则返回end()
lower_bound(key_value) ,返回第一个大于等于key_value的定位器
upper_bound(key_value),返回最后一个大于等于key_value的定位器
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *p1=headA,*p2=headB;
set<ListNode *> s;
while(p1){
s.insert(p1);
p1=p1->next;
}
while(p2){
if(s.count(p2)){return p2;}
else{p2=p2->next;}
}
return NULL;
}
};
(不用额外空间)两个指针 将题目转化为 链表是否有环 或者 将两个表接在一起**
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *p1=headA,*p2=headB;
while(p1!=p2){
if(!p1){p1=headB;}
else{p1=p1->next;}
if(!p2){p2=headA;}
else{p2=p2->next;}
}
return p1;
}
};