输入一个链表,输出该链表中倒数第 k 个结点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* findKthToTail(ListNode* head, int k) { int n = 0; for (auto p = head; p; p = p->next) n++; if (k > n) return NULL; auto p = head; for (int i = 0; i < n - k; i++) p = p->next; return p; } };
标签:head,ListNode,int,next,链表,节点,倒数第 From: https://www.cnblogs.com/leetothemoon/p/16982221.html