题目:
链表中倒数第k个结点
题目描述:
输入一个链表,输出该链表中倒数第k个结点。
解题:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead == NULL) return NULL;
if(k == 0) return 0;
ListNode *root, *node;
int i = 1;
root = revese(pListHead);
node = root;
while(i<k){
node = node->next;
i++;
}
revese(root);
return node;
}
private:
ListNode * revese(ListNode* n){
ListNode *pre = NULL, *last;
while(n){
last = n->next;
n->next = pre;
pre = n;
n = last;
}
return pre;
}
};