【LeetCode】19. Remove Nth Node From End of List (2 solutions)

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.

这题的难点在于one pass

没到尾部就没法进行倒退n个节点的操作。

但是到达尾部之后,再进行倒退删除操作,就不满足one pass了

由此诞生解法一:使用数组记录所有节点的位置,通过下标计算(size-n)立刻定位到需要删除的节点了

建立vector存放ListNode*,每个指针指向一个链表节点

时间复杂度:O(n)

空间复杂度:O(n)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) 
    {
        vector<ListNode*> v;
        ListNode* cur = head;
        v.push_back(cur);
        int size = 0;
        while(cur != NULL)
        {
            cur = cur->next;
            //push_back the last NULL
            v.push_back(cur);
            size ++;
        }
        //delete index
        int ind = size - n;
        if(ind-1 < 0)
        //delete the head
            return head->next;
        else
        {
            v[ind-1]->next = v[ind+1];
            return head;
        }
    }
};

仔细分析之后觉得浪费空间太多。

我们只是通过尾节点位置确定需要删除节点(n-1个偏移量),不需要其他的位置信息。

只需要两个位置相差n-1的指针,当前面的指针指向尾节点时,后面的节点即指向需要删除的节点。

由此产生解法二:

时间复杂度:O(n)

空间复杂度:O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode* tail = head;
        while(--n)
            tail = tail->next;
        
        ListNode* del = head;
        ListNode* predel = NULL;
        while(tail->next != NULL)
        {
            tail = tail->next;
            predel = del;
            del = del->next;
        }
        if(predel == NULL)
        //delete head
            return head->next;
        else
        {
            predel->next = del->next;
            return head;
        }
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4079879.html