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.
Note:
Given n would always be valid.
Try to do the in one pass.
Subscribe to see which companies asked this question
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Removenthfromend (ListNode head,intN) {if(Head = =NULL|| Head.next = =NULL)return NULL; ListNode Slow=Head; ListNode Fast=Head; while(n>1) {Fast=Fast.next; N--; } ListNode Pre=NewListNode (-1); Pre.next=slow; while(Fast.next! =NULL) {Pre=Pre.next; Slow=Slow.next; Fast=Fast.next; } Pre.next=Pre.next.next; if(slow = = head)returnpre.next;//If you delete an inverted n node that is the head node, do something special .Else returnHead; }}
Remove Nth Node from End of List Java Solutions