双指针法:用两个指针一个循环来完成(有时候两个循环才能完成的)一件事情
反转链表 https://leetcode-cn.com/problems/reverse-linked-list/submissions/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=NULL,*cur=head;
while(cur!=NULL)
{
ListNode* temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
};
反转字符串 https://leetcode-cn.com/problems/reverse-string/submissions/
class Solution {
public:
void swap(char& a,char& b)
{
char temp=a;
a=b;
b=temp;
}
void reverseString(vector<char>& s) {
if(s.size()==1) return;
for(int i=0,j=s.size()-1;i<=(s.size()-2)/2;i++,j--)
{
swap(s[i],s[j]);
}
}
};
移除元素 https://leetcode-cn.com/problems/remove-element/submissions/
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow=0,fast=0,len=nums.size();
while(true)
{
while( (fast<=len-1)&&nums[fast]==val ) fast++;
if(fast>len-1) break;
nums[slow]=nums[fast];
slow+=1;
fast+=1;
}
return slow;
}
};
注意C语言的逻辑运算符(&& ||)是从左到右运算的
|