题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
解
java
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p1 = dummy;
ListNode p2 = dummy;
for (int i = 0; i < n; i++) {
p2 = p2.next;
}
while (p2 != null && p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
p1.next = p1.next.next;
return dummy.next;
}
}