"019-remove Nth node from End of list (removes the reciprocal nth node of a single linked list)""leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"Original Question
Given A linked list, remove the nth 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.
Main Topic
Delete the last nth node of the single-linked list, note that n is valid for the input and completes the operation in one traversal.
Thinking of solving problems
First, let a pointer go to the nth node, then a pointer to the head node, and then two pointers go together, until the previous pointer to the end, the last pointer is the penultimate n+1 node, delete the bottom of the nth node can be.
Code Implementation
Linked list Node class
publicclass ListNode { int val; ListNode next; ListNode(int x) { val = x; null; }}
Algorithm implementation class
Public classSolution { PublicListNodeRemoventhfromend(ListNode Head,intN) {ListNode pa = head; ListNode PB = head;//Find nth node for(inti =0; I < n && pa! =NULL; i++) {pa = Pa.next; }if(PA = =NULL) {head = Head.next;returnHead }//PB vs. PA difference n-1 Nodes //When Pa.next is NULL,PB in the penultimate n+1 position while(Pa.next! =NULL) {pa = Pa.next; PB = Pb.next; } pb.next = Pb.next.next;returnHead }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special InstructionsWelcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/46997239"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "019-remove Nth node from End of list (removes the reciprocal nth node of a single linked list)"