文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>100题_09 查找链表中倒数第k个结点

100题_09 查找链表中倒数第k个结点

时间:2011-03-07  来源:小橋流水

题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。

 

这题可以使用两个指针,第一指针首先向后找k个节点,然后两外一个指针同步开始向后,当第一个到最后时,第二个指针就指向了倒数第k个节点。

 

废话少说,上码:

View Code #pragma once
#include <cstdlib>

using namespace std;

template <typename T>
class List;

template <typename T>
class ListNode
{
    friend class List<T>;    
public:
    ListNode(const T &data, ListNode *next);
    T GetData();
private:
    T data;
    ListNode *next;
};

template <typename T>
class List
{
public:
    List(void);
    ~List(void);
    void Insert(const T &data);
    T GetFromTail(int i); // 获取倒数第i个结点的值,最后一个结点为倒数第0个
private:
    ListNode<T> *first;
};

template <typename T>
ListNode<T>::ListNode(const T &data, ListNode *next):data(data), next(next)
{
}

template <typename T>
T ListNode<T>::GetData()
{
    return data;
}

template<typename T>
List<T>::List():first(NULL)
{
}

template <typename T>
void List<T>::Insert(const T &data)
{
    if (!first)
        first = new ListNode<T>(data, NULL);
    else
    {
        ListNode<T> *tmp = first;
        while (tmp->next)
            tmp = tmp->next;
        tmp->next = new ListNode<T>(data, NULL);
    }
}

template <typename T>
T List<T>::GetFromTail(int i)
{
    ListNode<T> *t1 = first, *t2 = first;
    for (int j = 0; j < i; j++)
    {
        if (!t1->next)
            throw "out of index";
        t1 = t1->next;
    }
    while (t1->next)
    {
        t1 = t1->next;
        t2 = t2->next;
    }
    return t2->data;
}

template <typename T>
List<T>::~List()
{
    ListNode<T> *tmp;
    while (first)
    {
        tmp = first;
        first = first->next;
        delete tmp;
    }
}

 

下面是测试代码:

View Code #include "List.h"
#include <iostream>

using namespace std;

int main()
{
    List<int> ls;
    for (int i = 0; i < 100; i++)
        ls.Insert(i);
    cout<<ls.GetFromTail(0)<<endl;
    return 0;
}

 

相关阅读 更多 +
排行榜 更多 +
别惹神枪手安卓版

别惹神枪手安卓版

冒险解谜 下载
坦克战争世界

坦克战争世界

模拟经营 下载
丛林反击战

丛林反击战

飞行射击 下载