Returns the nth node of a single-chain table.

Source: Internet
Author: User

Returns the nth node of a single-chain table.

My wife interviewed Apple's radio protocol testing post (not for Development) this morning and gave this question. At that time, she traversed twice (one time finding the total number of nodes M, I can't think of a better way to find the M-N node)


But I always think that the companion pointer can be traversed only once. I thought about it. I have to solve it:


#include 
 
  using namespace std;struct Node{    Node(int d, Node *n):data(d), next(n){}    int data;    struct Node *next;};struct List{    List(const char *c):listHead(0, NULL)    {        Node *p = &listHead;        for (; *c; c++)        {            p->next = new Node(*c, NULL);            p = p->next;            listHead.data++;// node count        }    }    void printList()    {        Node *p = listHead.next;        while (p)        {            cout << (char) (p->data) << ' ';            p = p-> next;        }        cout << endl;    }    Node listHead;};Node *FindNthNodeFromBottom(List &l, int N){    Node *p = l.listHead.next;    Node *q = p;    int step = 0;    while (p != NULL)    {        if (step >= N)        {            q = q->next;//if p left q behind N step, then q start move        }else{            step++;        }        p = p->next;    }    return q;}int main(){    List l("wanghaipeng");    l.printList();    int N = 4;    Node *p = FindNthNodeFromBottom(l, N);    cout << "the " << N <<"th node from bottom of list is : " << (char)(p->data) << endl;    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.