public class Remove_Nth_Node_From_End_of_List {
static int i = 0;
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp = new ListNode(0,head);
ListNode pre = removeNode(temp, n);
if (pre == temp) {
return pre.next;
} else return head;
}
public static ListNode removeNode(ListNode temp, int n) {
if (temp.next == null) {
return temp;
}
ListNode pre = temp;
temp = temp.next;
removeNode(temp, n);
i++;
if (i == n) {
pre.next = temp.next;
}
return pre;
}
public static void main(String[] args) {
ListNode h2 = new ListNode(2);
ListNode h1 = new ListNode(1,h2);
removeNthFromEnd(h1, 2);
}
public ListNode removeNthFromEnd1(ListNode head, int n) {
ListNode dummy = new ListNode(-1,head);
ListNode slow = dummy;
ListNode fast = dummy;
while (n-- >= 0) {
fast = fast.next;
}
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
|