题目链接点击打开链接
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode head2=new ListNode(0);
head2.next=head;
ListNode forward=head;
for(int i=1;i<n;i++)
{
forward=forward.next;
}
ListNode tarPre=head2;
while(forward.next!=null)
{
forward=forward.next;
tarPre=tarPre.next;
}
ListNode result=tarPre.next;
if(result==head)
{
return result.next;
}
if(result.next==null)
{
tarPre.next=null;
}
else
{
tarPre.next=result.next;
}
return head;
}
}