Sword refers to Offer 22-the last kth node in the linked list

topic

train of thought

Solution one

Since it is necessary to output the kth node, it is necessary to find the end node first, and then traverse forward from the end node. However, the linked list structure given in the title is a one-way linked list, and the forward node of a certain node cannot be found. Therefore, it needs to be implemented with the help of an additional storage structure. When it comes to reverse order, the stack is a good choice. We can traverse the linked list from the beginning, push each node onto the stack, and then pop k-1 nodes. Finally, when returning, pop up the kth node

public ListNode GetKthFromEnd(ListNode head, int k) {
    
    
	if (head == null)
		return head;
	Stack<ListNode> stack = new();
	ListNode cur = head;
	while (cur != null)
	{
    
    
		stack.Push(cur);
		cur = cur.next;
	}

	if (k > stack.Count)
		return null;
	
	for (int i = 1; i < k; i++)
	{
    
    
		stack.Pop();
	}

	return stack.Pop();
}

Solution two

The previous idea must first traverse the linked list completely, and then traverse the k elements in reverse to find the required node. So can we find the k-th node from the bottom in the first traversal? The answer is yes. This can be easily done with only two pointers.
First define two pointers "left" and "right" both point to the position of the head node

Then during the traversal process, first let the right pointer go k-1 steps, and then the left and right pointers move right together. Finally, when the traversal of the right pointer is completed, the left pointer stays at the kth position from the bottom

code show as below

public ListNode GetKthFromEnd2(ListNode head, int k)
{
    
    
	if (head == null)
		return head;
	ListNode left = head;
	ListNode right = head;
	while (right.next != null)
	{
    
    
		if (k-1 <= 0)
		{
    
    
			left = left.next;
		}
		right = right.next;
		k--;
	}
	return left;
}

Guess you like

Origin blog.csdn.net/LWR_Shadow/article/details/126864054