You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
529 B

package class28;
public class Problem_0019_RemoveNthNodeFromEndofList {
public static class ListNode {
public int val;
public ListNode next;
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
n--;
if (n == -1) {
pre = head;
}
if (n < -1) {
pre = pre.next;
}
cur = cur.next;
}
if (n > 0) {
return head;
}
if (pre == null) {
return head.next;
}
pre.next = pre.next.next;
return head;
}
}