求链表中倒数第k个节点

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

typedef struct node
{
int data;
struct node* next;
}ListNode; ListNode* FindKthToTail(ListNode* pListHead, unsigned int k); int main()
{
int i;
const int N = ;
ListNode *head, *p; //随机数种子
srand((unsigned int)time()); //生成链表
head = p = new ListNode;
head->data = rand() % ;
head->next = nullptr;
for ( i = ; i < N; i++)
{
p = p->next = new ListNode;
p->data = rand() % ;
p->next = nullptr;
} //输出链表
for (p = head; p; p = p->next)
{
cout << " " << p->data;
}
cout << endl; //产生随机数
i = rand() % ;
cout << "随机数n=" << i << endl; //输出倒数第k个数
p = FindKthToTail(head, );
if (nullptr == p)
{
cout << "find error" << endl;
}
else
{
cout << "find result: " << p->data << endl;
} cin.get();
return ;
} ListNode* FindKthToTail(ListNode* pListHead, unsigned int k)
{
if (nullptr == pListHead || !k)
return nullptr; int i;
ListNode *p, *q;
p = q = pListHead; for ( i = ; i < k-; i++)
{
if (nullptr==p->next)
{
return nullptr;
}
else
{
p = p->next;
}
}
while (nullptr != p->next)
{
p = p->next;
q = q->next;
} return q;
}
上一篇:学习mongo系列(三) update() save()


下一篇:记一次protobuf和hbase自带protobuf版本冲突的解决