Home > Java > javaTutorial > 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
Release: 2023-04-28 15:52:14
forward
1233 people have browsed it
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;
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template