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.

Notice
The minimum number of nodes in list is n.
Example
Given linked list: 1->2->3->4->5->null, and n = 2.
After removing the second node from the end, 
the linked list becomes 1->2->3->5->null.

Challenge
Can you do it without getting the length of the linked list?
We are here

Lintcode_ladder

Method

  1. initialize two pointer with n steps, then trying to find and delete the previous pointers
  2. x

Example

  1. 1
/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // write your code here
        if (!head) {
            return nullptr;
        }
        ListNode* prev = head;
        ListNode* target = head;
        ListNode* mov = head;
        int count = n;
        while (mov) {
            if (count < 1) {
                target = target->next;
            }
            if (count < 0) {
                prev = prev->next;
            } 
            mov = mov->next;
            count--;
        }
        // Nth Node is not existed
        if (count > 0) {
            return nullptr;
        } else if (count == 0) {
        // Nth node is the head
            return head->next;
        } else {
        // Nth node is in the middle
            prev->next = target->next;
            return head;
        }
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""