Leetcode(16)

来源:互联网 发布:tcp ip网络编程 源码 编辑:程序博客网 时间:2024/05/19 02:19

https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.


Solution:

用两个指针来处理问题,一个指针先移动n位,一个指针指向Head,然后一起移动,当前指针为空时,删除后指针指向的Node。

ListNode* RemoveNthFromEnd::removeNthFromEnd(ListNode *head, int n) {    if(head == nullptr || n == 0) {        return nullptr;    }    ListNode* pAhead = head;    for(unsigned int i = 0; i < n - 1; ++i) {        if(pAhead ->m_pNext != nullptr) {            pAhead = pAhead -> m_pNext;        } else {            return head;        }    }    ListNode** pBehind = &head;    while (pAhead -> m_pNext != nullptr) {        pAhead = pAhead -> m_pNext;        pBehind = &((*pBehind) -> m_pNext);    }    *pBehind = (*pBehind) -> m_pNext;    return head;}

原创粉丝点击