40.链表中的倒数第k个结点

2019-11-06  本文已影响0人  HamletSunS

思路:
链表的题目,要么内存逻辑代替法、要么快慢指针、要么先后指针,要么多指针,本题可以用先后指针(一个先出发,一个后出发)

代码:

/*
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;
        ListNode *forward=pListHead;
        ListNode *target=pListHead;
        for(int i=0;i<k;++i){
            if(forward==NULL)
                return NULL;
            forward=forward->next;
        }
        
         while(forward){
             forward=forward->next;
             target=target->next;
         }
        return target;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读