用快慢指针,时间复杂度O(n), 空间复杂度O(1)
# 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:
# 一趟扫描,空间复杂度O(1),快慢指针
dummy = ListNode(0, head)
fast = head
slow = dummy
for _ in range(n):
fast = fast.next
while fast:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.next
'''
# 一趟扫描,把节点入栈,T=O(L),S=O(L)
if not head:
return []
dummy = ListNode(next = head)
cur = dummy
stack = []
while cur:
stack.append(cur)
cur = cur.next
for _ in range(n):
stack.pop()
cur = stack[-1]
cur.next = cur.next.next
return dummy.next
'''
'''
#进行两趟扫描,第一趟扫描找到要删除的节点,第二趟扫描进行删除
if not head:
return []
length = 0
cur = head
while cur:
length += 1
cur = cur.next
if length - n == 0:
head = head.next
return head
count = 0
cur = head
while cur:
count += 1
if count == length - n:
cur.next = cur.next.next
break
cur = cur.next #!链表用while循环,别忘了每次当前节点更新为下一个节点
return head
'''