This question is quite easy, we could use the method of two pointers to solve it. Actually, we can use two pointers to solve most of the list questions.
Pay attention to the use of "nodePre", which indicates the element before the node to move. We may get a more concise code if we do not use this variable, but I think the code may be more clear to read if we choose to use it.
At first, I also want to change the values instead of changing the pointers of two nodes, but when n=1, this would not work :(
class Solution
{
public:
ListNode *removeNthFromEnd(ListNode *head, int n)
{
if (head == NULL || n == 0)
return head;
ListNode* nodeToMove = NULL;
ListNode* nodePre = NULL;
ListNode* firstNode = head;
while (--n)
{
firstNode = firstNode->next;
}
nodeToMove = head;
while (firstNode->next != NULL)
{
nodePre = nodeToMove;
firstNode = firstNode->next;
nodeToMove = nodeToMove->next;
}
if (nodePre == NULL) //remove the first element
{
return head->next; //do not free the memory
}
else
{
nodePre->next = nodeToMove->next;
return head;
}
}
};