ps:所有答案都是使用vs2013编写,答案仅供参考
题目
-
有一张单链表,编写函数求倒数第k个结点
-
编写函数,要求逆置单链表
-
如何快速查找一个单链表的中间位置,编写函数实现
答案部分
第一题
Node* FindK(PList plist,int k)
{
assert(plist != NULL);
Node* p = plist;
Node* q = plist;
int i = 0;
while (i<k-1)
{
if (p->next == NULL)
return 0;
p = p->next;
i++;
}
while (p->next != NULL)
{
p = p->next;
q = q->next;
}
return q;
}
第二题
void Inversion(PList plist)
{
assert(plist != NULL);
Node* p = plist->next;
Node* q = plist;
plist->next = NULL;
while (p != NULL)
{
q = p;
p = p->next;
q->next = plist->next;
plist->next = q;
}
}
第三题
Node* FindMid(PList plist)
{
assert(plist != NULL);
Node* p = plist;
Node* q = plist;
while (p)
{
if (p->next != NULL)
{
p = p->next->next;
q = q->next;
}
else
{
p = p->next;
q = q->next;
}
}
return q;
}
如果看答案看不太懂,请结合https://blog.csdn.net/Heart_of_collaps/article/details/100144257观看
如果对于链表不了解,可以点击https://blog.csdn.net/Heart_of_collaps/article/details/100189310查看
里面会有详细的叙述,这里仅公布答案