剑指offer——24链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。
 
题解:
  1、普通解法,先遍历一遍计算链表长度,然后遍历到倒数第k个节点;
  2、只遍历一遍,使用双指针,使得头尾指针位差为k,那么当尾指针为空时,头指针就是倒数第k个位置。
 
  
 1 //遍历两次,垃圾
 2 class Solution01 {
 3 public:
 4     ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
 5         if (pListHead == nullptr || k <= 0)return nullptr;
 6         int listLenght = 0;
 7         ListNode *res = nullptr, *p = pListHead;
 8         while (p != nullptr)
 9         {
10             listLenght++;
11             p = p->next;
12         }
13         if (listLenght < k)return res;
14         res = pListHead;
15         int nums = 0;
16         while (nums < (listLenght - k))
17         {
18             res = res->next;
19             nums++;
20         }
21         return res;
22     }
23 };
24 
25 //遍历一次,双指针
26 class Solution02 {
27 public:
28     ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
29         if (pListHead == nullptr || k <= 0)return nullptr;
30         ListNode *L, *Lk;
31         L = Lk = pListHead;
32         int i = 0;
33         for (; Lk != nullptr; ++i)
34         {
35             if (i >= k)
36                 L = L->next;
37             Lk = Lk->next;
38         }
39         if (i < k)return nullptr;
40         return L;        
41     }
42 };

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11668783.html