[Data structure]: Find the nth element in the linked list

Source: Internet
Author: User

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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.