Sword refers to Offer series Sword refers to Offer 22: the kth node from the bottom in the linked list

Title description:

Input a linked list and output the kth node from the bottom of the linked list. In order to conform to the habits of most people, this question starts counting from 1, that is, the end node of the linked list is the first node from the bottom. For example, a linked list has 6 nodes. Starting from the head node, their values ​​are 1, 2, 3, 4, 5, and 6. The third node from the bottom of this linked list is the node with the value 4.

Example:

Given a list: 1-> 2-> 3-> 4-> 5 , and K = 2 . 
The resulting list. 4 -> 5 .

Analysis: It may be more dishes, the first idea is a more dumb method:

  1. First calculate the total length of the linked list sum
  2. Then the head node of the linked list moves backward sum-k;

Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    int coutlen(ListNode* head)
    {
        auto x = head;
        int i=0;
        while(x)
        {
            i++;
            x = x->next;
        }
        return i;
    }
    ListNode* getKthFromEnd(ListNode* head, int k) {
        int len =coutlen(head);
        for(int i=0;i<len - k ;i++)
        {
            head = head ->next;
        }
        return head;
    }
};

The second method is to use double pointers:

  1. First define a fast pointer fast and a full pointer slow
  2. Let the fast pointer move k places first
  3. Then both move backwards until the fast pointer is empty and output slow
/**
 * 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) {
        auto fast = head;
        auto slow = head;
        for(int i = 0;i<k;i++)
        {
            fast=fast->next;
        }

        while(fast)
        {
            fast = fast->next;
            slow = slow->next;
        }
        return slow;
    }
};

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/110794529