剑指offer系列——链表中倒数第K个节点

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* p, unsigned int k) {
    if(p == NULL){
        return NULL;
    }
    if(k == 0){
        return NULL;
    }
    ListNode *a = p, *b = p;
    unsigned int count = 0;
    while(b->next != NULL){
        b = b->next;
        count++;
        if(count >= k){
            a = a->next;
        }
    }
    if(count >= (k-1)){
        return a;
    }else{
        return NULL;
    }
    
}
};
发布了51 篇原创文章 · 获赞 29 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qwer7512090/article/details/104927162
今日推荐