跪求算法:在一个链表找出(定位)倒数第K个元素,要C/C++的啊!!!

来源:百度知道 编辑:UC知道 时间:2024/05/30 21:39:36
最好是时间复杂度是O(n)的,救急!!!!!!!!!!!!!!!!!

倒数第k个(对应节点数为n的链表)节点的编号为n+1-k,所以从第一个节点移动n-k次即可。
struct node * fun(struct node *head,int k)
{
int len=0,i=0;
struct node * p=head;
while(p )
{
len++;
p=p->next ;
}
p=head;
for (i=1;i<len+1-k;i++)
p=p->next ;
return p;
}
接受到p后可以访问输入,如
test=fun(head,4);
printf("%d\n",test->data );