笨蛋法
# 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: ListNode, n: int) :
size = 1
count = head
while count.next!=None:
size +=1
count = count.next #先计算一下数组长度
cur = head
#这里要根据size的大小分情况
if size >1:
if size == n:
head = head.next
return head
else:
for _ in range(size-n-1):
cur = cur.next
cur.next = cur.next.next
return head
else:
head = None
return head
快慢指针法(双指针法)
# 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: ListNode, n: int) -> ListNode:
sentinalNode = ListNode(next=head)
slow, fast = sentinalNode, sentinalNode
#快指针先走n+1的原理是:此时slow在哨兵节点,fast在把n倒数看为正数的先驱节点
#即此时slow与fast的相对位置 与fast最终指向NULL时,slow指向倒数待删除节点的先驱节点时它俩的相对位置
#成镜像对称,fast指向NULL时, 此时的fast就是一开始的slow,此时的slow就是一开始的fast
for _ in range(n+1):
fast = fast.next
while fast != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return sentinalNode.next