双指针
快慢指针
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* slow=head;
ListNode* fast=head;
while((fast!=NULL)&&(fast->next!=NULL)){
slow=slow->next;
fast=fast->next->next;
if(fast==slow){//如果存在环,快指针迟早会追上慢指针
return true;
}
}
return false;
}
};
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* slow=head;
ListNode* fast=head;
while((fast!=nullptr)&&(fast->next!=nullptr)){
slow=slow->next;//n+1
fast=fast->next->next;//2n+1;
}
return slow;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* slow=head;
ListNode* fast=head;
while(n-->0){//快指先行n步
fast=fast->next;
}
if(fast==nullptr){
return head->next;
}
while((fast!=nullptr)&&(fast->next)!=nullptr){
slow=slow->next;
fast=fast->next;
}
slow->next=slow->next->next;
return head;
}
};
其他应用
LeetCode 167. 两数之和 II - 输入有序数组
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left=0;
int right=numbers.size()-1;
vector<int> ans;
while(left<right){//不断调整,大了小一点,小了大一点
if(numbers[left]+numbers[right]==target){
break;
}else if(numbers[left]+numbers[right]>target){
right--;
}else if(numbers[left]+numbers[right]<target){
left++;
}
}
ans.push_back(left+1);
ans.push_back(right+1);
return ans;
}
};
class Solution {
public:
void reverseString(vector<char>& s) {
int left=0;
int right=s.size()-1;
while(left<right){
char temp=s[left];
s[left]=s[right];
s[right]=temp;
left++;
right--;
}
}
};