[Algorithm] chain in the penultimate node k

Topic Source: cattle off net offer to prove safety

Title: Enter a linked list, the linked list output reciprocal k-th node.

Problem-solving ideas: the use of two pointers, a first pointer (font) data points to the k-th forward node, the second pointer (tail) of the head node to the data, when the font pointer to the tail, the tail pointer is k data points penultimate nodes.

Codes are as follows:

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        ListNode * font = pListHead;
		while ((k > 0)&&(font!=NULL)) {
			font = font->next;
			--k;
		}
		if ((font == NULL) && (k != 0))return NULL;
		ListNode* tail = pListHead;
		while (font != NULL)
		{
			font = font->next;
			tail = tail->next;
		}
		return tail;
    }
};

By Screenshot
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/u014128662/article/details/89027845