Problem:Given a linked list, search for the nth element after traversing only once. Minimize data overhead requirements.
Ideas:
Set two sentinel pointers. The first pointer first moves n positions, and then the second pointer moves from the first node with the first pointer. In this way, the distance between the first pointer and the second pointer is the length of N nodes. Therefore, when the first pointer moves to the end, the second Pointer Points to the last n nodes.
Code:
#include <iostream>using namespace std;struct Node{Node* next;int flag;};Node* reverse_find(Node* pt_head, int n){Node* pt_first_sentinel = pt_head;Node* pt_second_sentinel = pt_head;for (int i = 0; i < n; ++i){pt_first_sentinel = pt_first_sentinel->next;}while (pt_first_sentinel != NULL){pt_first_sentinel = pt_first_sentinel->next;pt_second_sentinel = pt_second_sentinel->next;}return pt_second_sentinel;}void link_list_test(){Node* pt_head = new Node;Node* pt_node = pt_head;pt_head->flag = 1;for (int i = 2; i <= 8; ++i){Node* pt_new_node = new Node;pt_new_node->flag = i;pt_node->next = pt_new_node;pt_node = pt_new_node;}pt_node->next = NULL;Node* result = reverse_find(pt_head, 8);cout << result->flag << endl;}int main(){link_list_test();return 0;}