/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @param n: An integer
* @return: The head of linked list.
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
if(head.next==null && n==1)
{
return null;
}
ListNode preNode=head;
ListNode currentNode=head;
ListNode goalNode=head;
for(int i=1;i<=n;i++)
{
currentNode=currentNode.next;
}
if(currentNode==null)
{
ListNode resultNode=head.next;
head=null;
return resultNode;
}
while(currentNode!=null)
{
currentNode=currentNode.next;
preNode=goalNode;
goalNode=goalNode.next;
}
preNode.next=goalNode.next;
goalNode=null;
return head;
}
}