链表中的双指针
环形链表
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head;
ListNode *fast = head;
while(fast != nullptr) {
fast = fast->next;
if(fast != nullptr) {
fast = fast->next;
}
if(fast == slow) {
return true;
}
slow = slow->next;
}
return nullptr;
}
};
相交链表
class Solution {
public:
//返回相交的节点
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* cur_a = headA;
while (cur_a)
{
ListNode* cur_b = headB;
while (cur_b)
{
if (cur_a == cur_b)
{
return cur_a;
}
cur_b = cur_b->next;
}
cur_a = cur_a->next;
}
return nullptr;
}
};
删除链表的倒数第N个节点
在这里插入代码片class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(-1); //哑节点
if(!head) return head;
dummy->next = head;
ListNode* p = dummy;
ListNode* q = dummy;
for(int i=0; i<n;i++)
{
q=q->next;
}
while(q->next)
{
p= p->next;
q= q->next;
}
p->next = p->next->next; //删除p->next的节点
ListNode* res = dummy->next;
delete dummy; //删除哑节点
return res;
}
};
数组中的双指针
反转字符串
情景1从两端向中间迭代数组,一个指针从始端开始,而另一个指针从末端开始。
class Solution {
public:
void reverseString(vector<char>& s) {
int left=0;
int right=s.size()-1;
while(left<right){
char t=s[left];
s[left]=s[right];
s[right]=t;
left++;right--;
}
return;
}
};
移除元素
情景2同时有一个慢指针和一个快指针,确定两个指针的移动策略。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i = 0;
int j = 0;
while (j < nums.size()) {
if(nums[j] != val) {
nums[i++] = nums[j++];
} else {
j++;
}
}
return i;
}
};
作者:jarvis1890
链接:https://leetcode-cn.com/problems/remove-element/solution/yi-chu-yuan-su-shuang-zhi-zhen-by-jarvis1890/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。