【剑指offer】【链表】22.链表中倒数第k个节点

题目链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/

遍历

时间复杂度:O(N)
空间复杂度: O(1)

class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        int n = 0;
        ListNode* temp = head;
        while(temp){
            temp = temp->next;
            n++;
        }
        k = n - k;
        while(k--){
            head = head->next;
        }
        return head;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

双指针

时间复杂度:O(N)
空间复杂度: O(1)

class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        if(!head) return nullptr;
        ListNode* fast = head;
        ListNode* low = head;
        int n = 0, i = k;
        while(fast){
            n++;
            fast = fast -> next;
            if(i > 0) i--;
            else low = low -> next;
        }
        if(n < k)
            return nullptr;
        return low;
    }
};

posted @ 2020-03-27 20:41  NaughtyCoder  阅读(66)  评论(0)    收藏  举报