package com.zerroi.leetcode.Three25; public class RemoveNthFromEnd { public static void main(String[] args) { // ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))); ListNode head = new ListNode(1, new ListNode(2)); SolutionFirst solutionFirst = new SolutionFirst(); solutionFirst.removeNthFromEnd(head, 2); } } class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } class SolutionFirst { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null) return null; ListNode cur = head; int length = length(head); if(length == 1) return null; if (length == n) return head.next; ListNode dummy = new ListNode(0, head); for (int i = 1; i <= length - n; i++) { cur = cur.next; dummy = dummy.next; } dummy.next = cur.next; return head; } private int length(ListNode head) { int length = 0; while (head != null) { length++; head = head.next; } return length; } }