[Offer prove safety study questions surface [15]: list of nodes penultimate k]

https://blog.csdn.net/derrantcm/article/details/46669025

 

 

typedef struct node
{
    int m_nValue;
    struct node* m_pNext;
}ListNode;

ListNode* findK(ListNode* pHead, int k) {
    if (NULL == pHead || k <=0) {
        return NULL;
    }
    ListNode *fastP = pHead;
    for (int i=0; i<k-1; i++) {
        fastP = fastP->m_pNext;
        if (fastP == NULL) {
            return NULL;
        }
    }
    ListNode *lowP = pHead;
    while (fastP->m_pNext) {
        fastP = fastP->m_pNext;
        lowP = lowP->m_pNext;
    }
    return lowP;
}


ListNode* pHead  = NULL;
    ListNode* pNode1 = NULL;
    ListNode* pNode2 = NULL;
    ListNode* pNode3 = NULL;
    
    
    pHead = (ListNode*)malloc(sizeof(ListNode));
    pNode1 = (ListNode*)malloc(sizeof(ListNode));
    pNode2 = (ListNode*)malloc(sizeof(ListNode));
    pNode3 = (ListNode*)malloc(sizeof(ListNode));
    
    pHead->m_nValue = 0;
    pHead->m_pNext  = pNode1;
    
    pNode1->m_nValue = 1;
    pNode1->m_pNext  = pNode2;
    
    pNode2->m_nValue = 2;
    pNode2->m_pNext  = pNode3;
    
    pNode3->m_nValue = 3;
    pNode3->m_pNext  = NULL;
    
    ListNode *kNode = findK(pHead, 3);

 

Published 81 original articles · won praise 68 · views 80000 +

Guess you like

Origin blog.csdn.net/li198847/article/details/104430015