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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-04-28 15:52:14
forward
1284 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:
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
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template