数据结构单向链表——找到并输出倒数第k个结点的数据

image

/**********************************************************************************************
*   func name       : LList_Last_k_find
*   function        : Find the last k node of link list and print data
*   func parameter  : 
*                       @Head :address of the head node 
*   return resuolt  : Find success result (true or failse)
*   author          : liaojx2016@126.com
*   date            : 2024/04/21
*   note            : None
*   modify history  : None
*   function section: v1.0
*
**********************************************************************************************/
bool LList_Last_k_Del(LList_t *Head, int k)
{
    //错误判断
  if (NULL == Head->next)
  {
    return false;
  }
  LList_t *p = Head;//参考指针
  LList_t *kp = Head;//指向倒数第k个结点的目标指针
  //参考指针先移动k个结点
  for (int i = 0; i < k; i++)
  {
    //printf("p.data=%d,p.next=%#x\n", p->data, p->next);
    //当还没移动k个单位,参考结点已指向尾指针,说明没有倒数第k个结点,直接退出函数,并输出提示
    if (p->next == NULL)
    {
      printf("Link list note count is less than %d\n", k);
      return false;
    }
    p = p->next;
  }
  //目标结点再移动一个单位
  kp = kp->next;
  //此时参考节点与目标结点已经相差k个单位
  //循环使得参考指针和目标指针同事移动一个单位,直到参考指针到达尾节点,目标指针到达倒数第k个结点的指定位置
  while (p->next)
  {
    p = p->next;
    kp = kp->next;
  }
  //输出目标结点的数据域
  printf ("data of the last %d node is %d\n",k,kp->data);
  return true;
}

posted @ 2024-04-23 10:22  沉舟道人  阅读(18)  评论(0编辑  收藏  举报