1. Problem
Removes the last nth node of the linked list and returns the list header. One traversal completes
return Its head. For example, 1->2->3->4->5, and n = 2. 1->2->3->5 do the in one pass.
2. Solution
With two pointers:
- P: The previous node pointing to the possible point of omission;
- Q:q-p = n;
For ease of handling, add an empty node in front of the linked list. The code is as follows:
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten PublicListNode Removenthfromend (ListNode head,intN) { One if(Head = =NULL ) A returnhead; - //Create a new head node so the we can always remove P.next -ListNode Newhead =NewListNode (0); theNewhead.next =head; -ListNode p = newhead;//Point to the previous node before to-be-deleted node -ListNode q = head;//q-p = n; - intCount = 1;//To find the first satisfied Q; + for(; q.next!=NULL&& count<n; count++, q =q.next); - //The to-be-deleted node exists + if(Count = =N) { A while(Q.next! =NULL ){ atp =P.next; -Q =Q.next; - } -P.next =P.next.next; - } - returnNewhead.next; in } -}
Remove Nth Node from End of List