Home >Java >javaTutorial >How to delete the Nth node from the last linked list in Java
The overall idea is to let the front pointer move n steps first, and then the front and rear pointers move together until the front pointer reaches the end.
First set up the advance pointer pre. The advance pointer is a little trick, which is explained in question 2.
The setting of the advance pointer pre The next node points to head. Let the front pointer be first and the back pointer be second. Both are equal to pre
first. Move forward n steps first
After that, first and second move forward together. At this time, the distance between them is n. When first reaches the end, the position of second is exactly the previous node of the n-th node from the last.
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode pre = new ListNode(0); pre.next = head; ListNode first = pre; ListNode second = pre; while (n>0){ first= first.next; n--; } while (first.next != null){ first=first.next; second=second.next; } second.next = second.next.next; return pre.next; } }
The above is the detailed content of How to delete the Nth node from the last linked list in Java. For more information, please follow other related articles on the PHP Chinese website!