一、题目
二、代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution
{
public ListNode removeNthFromEnd(ListNode head, int n)
{
if(head == null) return null;
// if(head.next==null) return null;
int length = 0;
ListNode my_head = new ListNode(0);
my_head.next = head;
ListNode cur = my_head;
while(cur!=null)
{
length++;
cur = cur.next;
}
// System.out.println(" length "+ length);
int index = 0;
int target_index = length-1-n;
// System.out.println(" index "+ index);
// System.out.println(" target_index "+ target_index);
cur =my_head;
while(cur!=null)
{
if(index == target_index )
{
// System.out.println("跳跃 "+index);
cur.next = cur.next.next;
break;
}
index++;
cur = cur.next;
}
return my_head.next;
}
}