Given A linked list, remove the nth node fromThe end of list andreturnIts head. For example, Given linked list:1-2-3-4-5, and n =2. After removing the second node fromThe end, the linked list becomes1-2-3-5. Note:given n would always be valid. Try to Do This inchOne pass.
Classic question. Double pointer, a pointer to go first n step, then two synchronized walk, until the first to go to the end, the second pointer is to delete the node. The only thing to note is the processing of the head node, for example,
1->2->null, n = 2; At this point, the head node is to be deleted.
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {public ListNode removenthfromend (listnode head, int n) { if (head = = null) return null; ListNode fast = head; ListNode slow = head; for (int i=0; i<n; i++) { fast = Fast.next; } If remove the first node if (fast = = null) { head = Head.next; return head; } while (fast.next! = null) { fast = Fast.next; slow = Slow.next; } Slow.next = Slow.next.next; return head; }}
Leetcode-remove Nth Node from End of List