1、题目链接
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
2、分析
设置了一个虚拟头结点,可以有效的避免删除头结点等一些边界情况。
cur = dummy; //赋值为虚拟头结点,关键
3、上代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null || n <= 0) return null;
ListNode dummy = new ListNode(-1); //设置一个虚拟头结点,可以避免一些特殊情况
dummy.next = head;
ListNode cur = head;
int length = 0;
while(cur != null) {
length ++;
cur = cur.next;
}
cur = dummy; //赋值为虚拟头结点,关键
int target = length - n;
while(target > 0) {
cur = cur.next;
target --;
}
cur.next = cur.next.next;
return dummy.next;
}
}