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'll always be valid . Try to do the in one pass.
Test instructions: Deletes the nth node of the bottom. Traverse as much as possible.
/** * definition for singly-linked list. * public class listnode { * int val; * ListNode Next; * listnode (int x) { val = x; } * } */public class Solution { public ListNode Removenthfromend (listnode head, int n) { if (head==null | | &NBSP;N<1) return head; listnode cur=head; while (cur!=null) { n--; cur= Cur.next; } if (n ==0) head=head.neXt; if (n<0) { cur=head; while (++n!=0) { cur=cur.next; } cur.next=cur.next.next; } return head; }}
PS: The left teacher provides a way to find the countdown to the first K. Go through it, k--at the same time, and finally judge the size of K. K==0 indicates that the head node is to be deleted. K>0, stating that K is wrong. K<0 time, and then go from the beginning again, but at this time K++,k=0 also found the first K-1. Simply delete the line at this time.
"Method 2" online fast and fast pointer method. Fast goes K-1 step first. Then slow and fast step-by-step. Fast arrives at the end of the slow to the penultimate K-1.
/*public class listnode { int val; listnode next = null; listnode (Int val) { this.val = val; }}*/public class Solution { public listnode findkthtotail (ListNode head,int k) { if (head==null | | k==0) return null; listnode fast=head; for (int i=0;i<k-1;i++) { ////Prevent K Invalid if (fast.next!=null) { fast=fast.next; }else{ return null; } } Listnode slow=head; while (fast.next!=null) { slow=slow.next; fast=fast.next; } return slow; }}
Leetcode 19. Remove Nth Node from End of List Java language