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