Leetcode a daily question: Interview question 02.02.kth-node-from-end-of-list-lcci (returns the kth node from the bottom)

Insert picture description here
Idea: The typical problem of fast and slow pointers. There are k-2 nodes between the fast pointer and the slow pointer. Then ++ the fast and slow pointers at the same time. When the fast pointer points to the end node of the linked list, the slow pointer points to the kth node from the bottom;
Insert picture description here

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

int kthToLast(ListNode *head, int k)
{
    
    
	ListNode *left = head, *right = head;
	int count = 1;
	while (count < k)
	{
    
    
		right = right->next;
		count++;
	}
	while (right->next)
	{
    
    
		left = left->next;
		right = right->next;
	}
	return left->val;
}

Guess you like

Origin blog.csdn.net/wyll19980812/article/details/108842200