【牛客网】链表中倒数第k个结点

    xiaoxiao2025-11-04  5

    题目: 输入一个链表,输出该链表中倒数第k个结点。

    AC的代码:

    class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if(pListHead==NULL)return NULL; int sum=1,sum1=1; ListNode *Node=pListHead; while(Node->next!=NULL){ sum+=1; Node=Node->next; } if(k==1)return Node;//如果是最后一个节点 Node=pListHead; while(Node->next!=NULL){ if(sum1==sum-k+1)return Node; Node=Node->next; sum1+=1; }//如果是其他节点 return NULL; } }; 剑指Offer上的代码 class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if (pListHead == NULL || k == 0)return NULL; ListNode* pAhead = pListHead; ListNode* pBehind = NULL; for (unsigned int i = 0; i < k - 1; i++){ if (pAhead->next!=NULL) pAhead = pAhead->next; else return NULL; } pBehind = pListHead; while (pAhead->next != NULL){ pAhead = pAhead->next; pBehind = pBehind->next; } return pBehind; }//只需遍历一遍 };
    转载请注明原文地址: https://ju.6miu.com/read-1303839.html
    最新回复(0)