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, head) # 由于可能会删除链表头部,用哨兵节点简化代码
left = right = dummy
for _ in range(n):
right = right.next # 右指针先向右走 n 步
while right.next:
left = left.next
right = right.next
left.next = left.next.next # 左指针的下一个节点就是倒数第 n 个节点
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;
}
}

文章介绍了在链表操作中,如何使用头节点和不使用头节点的方法来删除给定位置的节点,通过快慢指针实现,包括法1(使用虚拟头结点)和法2(直接操作)。
422

被折叠的 条评论
为什么被折叠?



