今天的题目是19. 删除链表的倒数第N个节点
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
p, q = head, head
for cur in range(n):
if p:
p = p.next
else:
return head
if not p:
head = head.next # 要删除结点是头结点
return head
while p.next:
p, q = p.next, q.next
q.next = q.next.next
return head
执行用时 :
40 ms, 在所有 Python3 提交中击败了47.91%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了7.45%的用户