入门级题解:剑指 Offer 22. 链表中倒数第k个节点

方法一,求出链表长度,再遍历做

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

    int getLen(ListNode* head){
	    ListNode* p = head;
	    int n = 0;
	    while(p){
		    p = p->next;
		    n++;
	    }
	    return n;
    }
};

方法2:快慢指针,先让快指针走k步,快指针到末尾的时候,慢指针到倒数第k个

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

好简单

上一篇:php文件包含的几种方式总结


下一篇:「题解」删除链表的倒数第 N 个结点