目录
LeetCode-19题
给定一个链表的头节点,删除链表的倒数第n个节点,并返回删除后的头节点
java
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// check
if (head == null || n <= 0) {
return head;
}
// 双指针
ListNode dummyHead = new ListNode(0, head);
ListNode p1 = dummyHead;
ListNode p2 = dummyHead;
for (int i = 0; i < n; i++) {
p2 = p2.next;
}
while (p2 != null && p2.next != null) {
p2 = p2.next;
p1 = p1.next;
}
// 此时删除的就是链表倒数第n个节点
p1.next = p1.next.next;
return dummyHead.next;
}
private static class ListNode {
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}