出题的大致函数声明:
node fun(node * head, int index),要实现函数里面的方法。
其中node是一个单向链表。
要实现的功能:返回倒数的第index个节点。
-------------------------------------------------------------
思路:
一般设置两个指针p1,p2
首先p1和p2都指向head
然后p2向前走n步,这样p1和p2之间就间隔n个节点
然后p1和p2同时向前步进,当p2到达最后一个节点时,p1就是倒数第n个节点了
node fun(node * head, int index)
{
node *ptr1,*ptr2;
int i = 0;
ptr1 = head;
ptr2 = head;
if( head == NULL || head->next == NULL )
return ptr1;
while(i<index)
{
ptr1 = ptr1->next;
if(ptr1 == NULL)
return head;
i++;
}
while(ptr1->next != NULL)
{
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
return *ptr2;
}
浙公网安备 33010602011771号