【LeetCode】Remove Nth Node From End of List

题目描述
  • 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.
    • Try to do this in one pass.
  • 题目要求do this in one pass ,即要求空间复杂度为O(1)
思路分析
  • 首先,要求删除倒数第 k 个节点,我们肯定要先找到倒数第 k 个节点,通过块满指针来实现,让fast指针先走 k 步,然后 fast 指针和 slow 指针同时走,当 fast 指针走到尽头,则 slow指针所指的节点即为我们要删除的节点,我们需要在遍历的过程中记录 slow 的前一个节点,方便我们找到节点后进行删除
  • 这里有一个特殊情况是,如果要删除的节点是头节点,它没有钱一个节点,所以直接返回头节点的下一个节点,这个情况要进行单独处理
  • 思路理清楚后,我们就可以动手写代码了
代码实现
ListNode *removeNthFromEnd(ListNode *head, int n) 
{
    //n 有可能>=链表长度,有可能<链表长度
    if(head == NULL)
        return head;
    ListNode* fast = head;
    ListNode* slow = head;
    ListNode* prev = NULL;//prev用来记录slow的前一个节点
    while(n-- && fast != NULL)
    {
        fast = fast->next;
    }
    //如果fast == NULL,即要删除的节点是头结点
    if(fast == NULL)
        return head->next;
    while(fast != NULL)
    {
        prev = slow;
        slow = slow->next;
        fast = fast->next;
    }
    prev->next = slow->next;
    return head;
}

猜你喜欢

转载自blog.csdn.net/Aurora_pole/article/details/81501722