题目:
解答:
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 };
原文:https://www.cnblogs.com/ocpc/p/12857193.html