Remove Nth Node From End of List

Question: Remove Nth Node From End of List

Description: Given a linked list, remove the n-th node from the end of list and return its head.


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: n will always be valid.

Solution

例如上图所示链表 2->3->4->5->6->7,现在需要删除倒数第二个节点(节点6,n=2),我们只需要找到待删除节点的前一个节点5就可以解决问题了。步骤如下:

  • 首先定义两个指针pLeft, pRight ,均指向头结点,然后pLeft不动,将pRight向前移动n次,指向节点4;
  • 下面pLeft和pRight同时向前移动,直到pRight指向尾节点,此时pLeft指向待删节点的前一个节点5;
  • 最后执行删除即可

Solution Code:

class Solution {
    /**
     * 注意以下几点:
     * (1)提示: n will always be valid. 所以不需要考虑n<=0 或者超过链表长度的问题
     * (2)若待删除节点不是头结点,则不需要维护头结点
     * (3)待删除节点是头结点的情况,需要注意
     */
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (head == NULL)
            return NULL;

        ListNode* pRight = head;
        ListNode* pLeft = head;
        ListNode* pHead = head;
        int count = 0;
        while(pRight != NULL && count < n){
            pRight = pRight->next;
            ++count;
        }
        // 待删除节点是头结点的情况
        if(pRight == NULL){
            pHead = head->next;
            free(head);
            return pHead;
        }
        // 查找待删除节点的前一个节点
        while(pRight->next != NULL){
            pRight = pRight->next;
            pLeft = pLeft->next;
        }
        // 执行删除
        ListNode* pDelete = pLeft->next;
        pLeft->next = pLeft->next->next;
        free(pDelete);
        return pHead;
    }
};

Reports: Runtime: 4 ms, faster than 100.00% of C++ online submissions for Remove Nth Node From End of List.

原文地址:https://www.cnblogs.com/iwangzhengchao/p/9975458.html