day8--the kth node from the bottom of the linked list

The last k nodes in the linked list 

double pointer method

It is to define two pointers p and q, first let p point to the head node of the linked list, and then let q point to the kth node.

Next, move p and q at the same time until q points to the end node of the linked list. At this time, the node pointed to by p is the kth node from the bottom

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode* findKthToTail(ListNode* head, int k) {
    if (head == NULL || k <= 0) {
        return NULL;
    }
    ListNode *p = head, *q = head;
    for (int i = 0; i < k - 1; i++) {
        if (q == NULL) {
            return NULL;
        }
        q = q->next;
    }
    if (q == NULL) {
        return NULL;
    }
    while (q->next != NULL) {
        p = p->next;
        q = q->next;
    }
    return p;
}

Delete the last nth node of the linked list

fast and slow pointer method

First let the fast pointer move to the n+1th node of the linked list; then move the fast and slow pointers at the same time until the fast pointer reaches the end of the linked list; at this time, the node pointed by the slow pointer is the node before the node to be deleted, and next The pointer points to the next node of the node to be deleted.

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *dummy=new ListNode(0);
        dummy->next=head;
        ListNode *slow=dummy, *fast=dummy;
        for(int i=0; i<=n; i++){
            fast=fast->next;
        }
        while(fast!=NULL){
            slow=slow->next;
            fast=fast->next;
        }
        slow->next=slow->next->next;
        return dummy->next;
    }
};

Guess you like

Origin blog.csdn.net/qq_54809548/article/details/130904492