面试题22. 链表中倒数第k个节点

题目:

 

 

解答:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* getKthFromEnd(ListNode* head, int k) 
12     {
13         if (NULL == head || k <= 0)
14         {
15             return NULL;
16         }
17         
18         ListNode *cur = head;
19         int num = 0;
20         while (cur != NULL)
21         {
22             num++;
23             cur = cur->next;
24         }
25         
26         if (k > num)
27         {
28             return NULL;
29         }
30         
31         cur = head;
32         for (int i = 0; i < num - k; i++)
33         {
34             cur = cur->next;
35         }
36         
37         return cur;
38     }
39 };

 

posted @ 2020-05-09 14:21  梦醒潇湘  阅读(208)  评论(0)    收藏  举报