Python
参考:灵茶山艾府
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(-1)
dummy.next = head
slow = dummy # slow, fast初始位置都在虚拟头结点上
fast = dummy
for i in range(0, n):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
Java
法1:使用头结点
注意使用虚拟头结点!!!
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null || head.next == null) {
return null;
}
ListNode dummy = new ListNode(-1); // 虚拟头结点
dummy.next = head;
ListNode slow = dummy, fast = dummy;
while (n > 0) {
fast = fast.next;
--n;
}
while (fast != null && fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
法2:不使用头结点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return null;
}
ListNode fast = head, slow = head;
while (n > 0 && fast != null) {
fast = fast.next;
--n;
}
if (fast == null) { // 删除正数第1个结点
return head.next;
}
while (fast.next != null) { // fast停留在最后的结点上, slow停留在被删除的前一个结点上
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}