一、题目
二、代码
class Solution
{
public ListNode removeNthFromEnd(ListNode head, int n)
{
if (head == null) return null;
int length = 0;
ListNode MyHead = new ListNode(0);
ListNode ProcessNode = new ListNode(0);
MyHead.next = head;
ProcessNode = MyHead;
while(ProcessNode.next!=null)
{
ProcessNode = ProcessNode.next;
length = length+1;
}
System.out.println("length " +length);
int drop = length - n;
ProcessNode = MyHead;
int count = 0;
while(count!=drop)
{
ProcessNode=ProcessNode.next;
count = count+1;
}
ProcessNode.next = ProcessNode.next.next;
return MyHead.next;
}
}
三、运行结果
四、附录
class Solution
{
public ListNode removeNthFromEnd(ListNode head, int n)
{
if(head.next == null) return null;
int length = 0 ;
ListNode pro_node = head;
ListNode my_head = new ListNode(0);
my_head.next = head;
while(pro_node != null)
{
length++;
pro_node = pro_node.next;
}
int index = length-n;
int count = 0;
pro_node = my_head;
while(pro_node!=null)
{
if(count == index)
{
pro_node.next=pro_node.next.next;
break;
}
count++;
pro_node = pro_node.next;
}
return my_head.next;
}
}