Leetcode|剑指 Offer 22. 链表中倒数第k个节点

2021-09-18 17:26:47 浏览数 (1)

1 先找到链表长度n,再从头遍历到n-k点返回

代码语言:javascript复制
class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        int n = 0;
        auto node = head;
        while (node) {
            node = node->next;
            n  ;
        }
        for (int i = 0; i < n; i  ) {
            if (i == n - k) return head;
            head = head->next;
        }
        return nullptr;
    }
};

2 双指针(中间隔k个点,同时前进)

代码语言:javascript复制
class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        auto preK = head;
        auto cur = head;
        for (int i = 0; i < k; i  )
            cur = cur->next;
        while (cur) {
            cur = cur->next;
            preK = preK->next;
        }
        return preK;
    }
};

0 人点赞