码迷,mamicode.com
首页 > 其他好文 > 详细

[剑指offer] 14. 链表中倒数第k个结点

时间:2018-12-01 21:51:26      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:tle   turn   14.   while   scribe   nbsp   class   title   思路   

题目描述

输入一个链表,输出该链表中倒数第k个结点。

思路:
利用一前一后两个指针,先拉出两个指针的距离为k-1,然后一起移动两个指针,直到后指针指向链表尾部,则前指针就是倒数第K个。
class Solution
{
public:
  ListNode *FindKthToTail(ListNode *pListHead, unsigned int k)
  {
    if (pListHead == NULL)
      return NULL;
    ListNode *low = pListHead;
    ListNode *high = pListHead;

    for (int i = 0; i < k - 1; i++)
    {
      if (high->next == NULL)
        return NULL;
      high = high->next;
    }

    while (high->next != NULL)
    {
      high = high->next;
      low = low->next;
    }
    return low;
  }
};

 

[剑指offer] 14. 链表中倒数第k个结点

标签:tle   turn   14.   while   scribe   nbsp   class   title   思路   

原文地址:https://www.cnblogs.com/ruoh3kou/p/10050781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!