Title Description:
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
1->2->3->4->5 N = 2. 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Problem Solving Ideas:
Set two pointers, two pointers are separated by n-1, and the two pointers move backwards at the same time, when the latter pointer has no successor, the node to which the previous pointer points is the node that needs to be deleted.
The code is as follows:
/** * 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 ppre = null; ListNode p = head; ListNode q = head;for (int i = 0; i < n-1; i++) q = Q.next;while (Q.next! = null) {Ppre = P;p = P.next;q = Q.next;} if (Ppre = = null) return head.next;ppre.next = P.next;return Head;}}
Java [Leetcode 19]remove Nth Node from End of List