Remove Nth Node From End of List
You have exceeded the time limit
Given a linked list, remove the nth node from the end of list and return its head.
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.
Note
The minimum number of nodes in list is n.
Challenge
O(n) time
/**
* 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 == NULL)
return NULL;
if (n <= 0)
return head;
ListNode fakeHead(-1);
fakeHead.next = head;
ListNode* preNode = &fakeHead;
ListNode* curNode = head;
ListNode* frontNode = head;
for (int i=1; i<n; i++)
{
if (frontNode)
frontNode = frontNode->next;
else
return head;
}
while (frontNode->next)
{
frontNode = frontNode->next;
curNode = curNode->next;
preNode = preNode->next;
}
preNode->next = preNode->next->next;
return fakeHead.next;
}
};