Algorithm-Remove Nth Node From End Of List

Algorithm Remove Nth Node from End of list

Description

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Submission

package com.cctoken.algorithm;


/**
 * @author chenchao
 */
public class RemoveNthNode {

  public static void main(String[] args) {
    ListNode head = new ListNode(1);
    ListNode res = new RemoveNthNode().removeNthFromEnd(head, 1);
    if (res != null) {

    }
  }

  public ListNode removeNthFromEnd(ListNode head, int n) {
    if (head == null) {
      return null;
    }
    ListNode start = new ListNode(0);

    ListNode fast = start;
    ListNode slow = start;
    slow.next = head;
    for (int i = 0; i < n; ++i) {
      fast = fast.next;
    }
    while (fast.next != null) {
      fast = fast.next;
      slow = slow.next;
    }
    slow.next = slow.next.next;
    return start.next;
  }


  public static class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
      val = x;
    }
  }
}

Solution

A list of the removed penultimate N nodes. The list of characteristics must be determined to traverse the complete list in order to know the specific location of each node.
The first idea is to get this question when traversing into the stack, the stack when he knew the penultimate N nodes which, as long as this node can be removed. But this process of considering the
space will certainly be very high, so the idea directly into the traversal time, do not remove the memory can achieve the purpose of
using the pointer speed, the gap between the two is always N, then when fast when the pointer reaches the end of the list, just in case the slow pointer penultimate the N + 1, then a pointer to the next node to slow remove it.
Then the final result is to start.next, start.next is used to mark a head of the list

6868357-c6b0526cdf76379e.png
image.png

Guess you like

Origin blog.csdn.net/weixin_34357436/article/details/90973829