寻找单链表的倒数第N个节点

来源:互联网 发布:自动化编程语言有哪些 编辑:程序博客网 时间:2024/05/16 08:04

老婆今早面试苹果的radio协议测试岗位(非开发),给了这个题目,当时她是两次遍历(一次找出总节点数M,一次找出第M-N节点),我也想不出更高明的办法


但总觉得伴随指针能做到只遍历一遍,想了想,得解:

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


0 0