[C/C++] Data structure linked list OJ question: kth node from the last in the linked list

describe

Input a linked list and output the k-th node from the last in the linked list.

 Method 1: Violent solution

        ​ ​ First traverse the entire linked list to obtain the length of the linked list len, then the kth node from the last is the integer len-kth node

struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) {
    struct ListNode* cur = pListHead;
    int len = 0;

    while (cur) {
        len++;
        cur = cur->next;
    }

    int num = len - k;
    cur = pListHead;
    if (num < 0) {
        return NULL;
    }
    while (num--) {
        cur = cur->next;
    }
    return cur;
}

Note: Special attention should be paid here to determine whether len-k is less than 0, because if k is greater than the length of the linked list, then the k-th node from the bottom will be a null pointer

Method 2: Fast and slow pointers

        Define the pointers slow and fast. First let the fast pointer go forward k steps, so that the two pointers are k positions apart. Then let the two pointers go together. When fast points to null, the slow pointer points to the kth from the bottom. Nodes, as shown in the figure:

Suppose you want to find the second to last node

 

struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) {
    struct ListNode* slow = pListHead;
    struct ListNode* fast = pListHead;
    //快指针先走k步
    while (k--) {
        if (fast == NULL) {
            return NULL;
        }
        fast = fast->next;
    }


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

Note: Here we also need to judge the same problem as method 1. When fast walks k steps forward and points to empty, it means that k is greater than the length of the linked list, and returns NULL< /span>

Guess you like

Origin blog.csdn.net/m0_74910646/article/details/134233425