```
public ListNode removeNthFromEnd(ListNode head, int n) {
if(n<=0){
return head;
}
Stack<ListNode> stack = new Stack<>();
ListNode headNode = head;
while (headNode!=null){
stack.push(headNode);
headNode = headNode.next;
}
int counter = 0;
ListNode lastNode = null;
ListNode nextNode = null;
while(!stack.empty()){
counter++;
ListNode listNode = stack.pop();
if(counter == n-1){
nextNode = listNode;
}
if(counter == n+1){
lastNode = listNode;
break;
}
}
if(counter == n+1){
lastNode.next = nextNode;
}else if(counter<n+1&&counter>=n-1){
head = nextNode;
}
return head;
}
```