Home  >  Article  >  Java  >  How to delete the Nth node from the last linked list in Java

How to delete the Nth node from the last linked list in Java

WBOY
WBOYforward
2023-04-28 15:52:141112browse
Problem-solving ideas
  1. 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.

  2. First set up the advance pointer pre. The advance pointer is a little trick, which is explained in question 2.

  3. 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

  4. first. Move forward n steps first

  5. 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.

Java code
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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete