Test instructions
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Try to do the in one pass. (easy)
Analysis: Although the topic is easy, but with one pass to do it still contains a few linked lists commonly used techniques, have reference value;
There is nothing difficult on the list algorithm, it is the code carefully, and then familiar with several processing methods.
1.Two pointers. The use of quick and slow hands, fast hands first walk n steps, and then go together, fast next to the end, slow to get to delete the previous bit;
2. Dummy node. The head position may be deleted, the problem is returned, and the return problem is handled with dummy node.
Code:
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Removenthfromend (listnode* head,intN) { AListNode Dummy (0); -Dummy.next =head; -Head = &dummy; thelistnode* chaser =head; -Listnode* runner =head; - for(inti =0; I < n; ++i) { -Runner = RunnerNext; + } - while(Runner-Next! =nullptr) { +Runner = RunnerNext; AChaser = ChaserNext; at } -listnode* temp = ChaserNext; -Chaser next = Chaser, NextNext; - Deletetemp; - returnDummy.next; - } in};
LeetCode19 Remove Nth Node from End of List