转载自:http://blog.csdn.net/zhtsuc/article/details/4534678
题目表述:
设计一个算法,找出一个无环的单链表里面倒数第k个元素,速度要快。
算法实现:
实现中的注释已经解释了算法的大概思想。
struct node{
int key;
node* next;
};
typedef node* List;
int findLastKthElement(List list, int k)
{
//遍历整个链表,
//声明一个临时指针指向头节点
//当遍历过元素个数小于K的时候,继续遍历
//当遍历过的元素个数等于k的时候,临时指针指向下一个元素,然后继续遍历
//当遍历到链表尾部的时候,则临时指针指向的节点就为倒数第k个元素。
if (list == NULL || k <= 0)
{
return -1; //查找失败。
}
List p = list;
List tempList = list;
int num = 0;
while(p)
{
if (num < k)
{
num++;
}
else if (num == k)
{
tempList = tempList->next;
}
p = p->next;
}
if (num < k)
{
return -1; //查找倒数第k个元素失败
}
return tempList->key;
}