I. Title Description
Given A linked list, remove the n th node from the end of the 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 would always be valid.
? Try to do the in one pass.
Two. Topic analysis
Given a linked list, it refers to the deletion of the n
penultimate n
node. The value of the hint here n
is legal by default. But in fact, the input of the N to make an exception to judge only a few sentences.
Using two pointers, the concept of a fast/slow pointer, one of the pointers goes first n
, then the slow pointer goes, and when the fast pointer goes to the end, the slow pointer goes to the previous position of the node that needs to be removed.
The main difficulty of this problem is to consider the boundary problem, as well as the special case (to remove the head node), such as input 1->2->3->4
, n=4
then need to delete 1
, at this point only the head pointer head = head->next
can be.
Three. Sample code
#include <iostream>struct listnode{intValue listnode*Next; ListNode (int x): Value (x),Next(NULL) {};}; Class Solution{public:listnode*removenthfromend(ListNode*head,intN) {if(head = = NULL)returnNULL; ListNode*fast= head; ListNode*slow= head; ListNode*temp= head; for(inti =0; I < n; i++) {fast = Fast->Next;if(FAST)Continue;Else Break; } while(FAST) {fast = Fast->Next; temp = slow; slow = slow->Next; }if(slow = = head) {head = head->Next;returnHead } temp->Next= slow->Next;DeleteSlowreturnHead }};
Results:
Four. Summary
The actual programming often encounter boundary problems, careless errors can easily cause the program to crash, the use of pointers and linked list skills need to further study.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode notes: Remove Nth Node from End of List