一个单向链表,查找倒数的第N个结点位置
主要思想:2个指针办法,前指针偏移N个位置,后指针指向链表头部
前后指针同时向后偏移,当前指针指向NULL,此时后指针就是倒数N个节点位置
代码如下:
/*
*@author: 赵秋然
*@date:2021年1月10日
*@description:链表倒数结点
*@param head:链表
*@param k:倒数的位置
*@return: 返回链表指针
*/
int getLength(ListNode *head)
{
ListNode *cur = head;
int len = 0;
while (cur)
{
cur = cur->next;
++len;
}
return len;
}
ListNode *getReciprocal(ListNode *head, int k)
{
if (head == NULL || k == 0)
{
return head;
}
int len = getLength(head);
if (k >= len)
{
return head;
}
ListNode *cur = head, *fcur = head;
while (k > 0)
{
fcur = fcur->next;
if (fcur == NULL)
{
return NULL;
}
--k;
}
while (fcur)
{
cur = cur->next;
fcur = fcur->next;
}
return cur;
}