1. 程式人生 > >劍指offer---鏈表中倒數第k個節點

劍指offer---鏈表中倒數第k個節點

劍指offer ret -- code off plist listnode urn logs

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        ListNode* p1 = pListHead;
        ListNode* p2 = pListHead;
        int temp = k;

        
if(pListHead == NULL || k <= 0) { return NULL; } temp--; while(temp--) { /* 鏈表的長度小於k */ p2 = p2->next; if(p2 == NULL) { return NULL; } } while
(p2->next != NULL) { p1 = p1->next; p2 = p2->next; } return p1; } };

劍指offer---鏈表中倒數第k個節點