双指针-数据结构

链表中的双指针

环形链表

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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值