Wins the offer - the inverse of the k th node in the linked list 24

Title Description

Input a linked list, the linked list output reciprocal k-th node.
 
answer:
  1, the general solution, again calculated to traverse the length of the list, and then traverse the penultimate node k;
  2, again only traverse a twin pointers, such that the head and tail pointers for the k difference, then when the tail pointer is empty, the head pointer is the reciprocal of the k-th position.
 
  
 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 };

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11668783.html