码迷,mamicode.com
首页 > 其他好文 > 详细

求链表中倒数第k个节点

时间:2015-08-01 23:12:58      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

注意鲁棒性和算法效率的典型例题:(头文件省略)

typedef struct node
{
    int data;
    struct node* next;
}ListNode;

ListNode* FindKthToTail(ListNode* pListHead, unsigned int k);

int main()
{
    int i;
    const int N = 50;
    ListNode *head, *p;

    //随机数种子
    srand((unsigned int)time(0));

    //生成链表
    head = p = new ListNode;
    head->data = rand() % 101;
    head->next = nullptr;
    for ( i = 0; i < N; i++)
    {
        p = p->next = new ListNode;
        p->data = rand() % 101;
        p->next = nullptr;
    }

    //输出链表
    for (p = head; p; p = p->next)
    {
        cout << " " << p->data;
    }
    cout << endl;

    //产生随机数
    i = rand() % 101;
    cout << "随机数n=" << i << endl;

    //输出倒数第k个数
    p = FindKthToTail(head, 3);
    if (nullptr == p)
    {
        cout << "find error" << endl;
    }
    else
    {
        cout << "find result: " << p->data << endl;
    }

    cin.get();
    return 0;
}

ListNode* FindKthToTail(ListNode* pListHead, unsigned int k)
{
    if (nullptr == pListHead || !k)
        return nullptr;

    int i;
    ListNode *p, *q;
    p = q = pListHead;

    for ( i = 0; i < k-1; i++)
    {
        if (nullptr==p->next)
        {
            return nullptr;
        }
        else
        {
            p = p->next;
        }
    }
    while (nullptr != p->next)
    {
        p = p->next;
        q = q->next;
    }

    return q;
}

 

求链表中倒数第k个节点

标签:

原文地址:http://www.cnblogs.com/jason1990/p/4694712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!