1. 程式人生 > 其它 >劍指Offer-第11天 雙指標(簡單)

劍指Offer-第11天 雙指標(簡單)

第一題

題目連結:https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/

個人題解:雙指標遍歷即可

程式碼:

class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(head->val == val) return head->next;
        ListNode *pre = head, *cur = head->next;
        while(cur != nullptr && cur->val != val) {
            pre = cur;
            cur = cur->next;
        }
        if(cur != nullptr) pre->next = cur->next;
        return head;
    }
};

執行截圖:

第二題

題目連結:https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/

個人題解:先讓一個指標走到 \(k\) 個位置,然後再來一個指標,讓它們之間的距離保持在一個固定值

程式碼:

class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        auto p=head, q=head;
        while(k--){
            if(p) p=p->next;
            else return NULL;
        }
        while(p) q=q->next, p=p->next;
        return q;
    }
};

執行截圖: