链表问题一般使用快慢指针来找中点或判是否有环
环形链表用快慢指针+辅助指针利用数学公式推导出结论然后模拟即可。
链表排序则模拟数组排序,归并排序+快慢指针找中点。
141. 环形链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==nullptr)return false;
ListNode* fast=head;
ListNode* slow=head;
while(slow){
if(slow->next)slow=slow->next;else break;
if(fast->next)fast=fast->next;else break;
if(fast->next)fast=fast->next;else break;
if(slow==fast)return true;
}
return false;
}
};
142. 环形链表 II
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
L - > C
L+cx = fast-slow = slow
*/
//L + C
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==nullptr)return NULL;
ListNode* fast=head;
ListNode* slow=head;
ListNode* ptr=head;
while(slow){
if(slow->next)slow=slow->next;else break;
if(fast->next)fast=fast->next;else break;
if(fast->next)fast=fast->next;else break;
//cout<<slow->val<<" "<<fast->val<<" "<<endl;
if(slow==fast){
while(ptr!=slow){
ptr=ptr->next;
slow=slow->next;
}
return slow;
}
}
return NULL;
}
};