标签:c++ pre orm next while for lang form null
链表中倒数第K个节点.
双指针, 然后一个指针延迟运行.
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *p = head;
ListNode *pk = head;
int index = 0;
bool check = false;
while(p){
p = p->next;
index ++;
if(index == k) check = true;
if(index > k){
pk=pk->next;
}
}
if(check) return pk;
return NULL;
}
};
// 可以让一个指针先走, 真的方便.
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode former = head, latter = head;
for(itn i = 0; i<k; i++){
former = former.next;
}
while(former != null) {
former = former.next;
latter = latter.next;
}
return latter;
}
}
标签:c++ pre orm next while for lang form null
原文地址:https://www.cnblogs.com/eat-too-much/p/14830646.html