思路:
先计算链表的长度,然后遍历到n - k
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
int n = 0;
for(auto p = head;p;p = p->next) n++;
auto dummy = head;
for(int i = 0; i < n - k; i++) dummy = dummy->next;
return dummy;
}
};
评论区