小黑代码
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
arr = []
node = head
while node:
arr.append(node)
node = node.next
l = len(arr)
if n > l:
return head
elif n == l:
return head.next
else:
arr[0-n-1].next = arr[0-n].next
return head
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6e346696b29a5f7363c143ad3a2ff882.png)
链表长度法
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
def get_length(link):
length = 0
while link:
length += 1
link = link.next
return length
link = head
length = get_length(link)
add_node = ListNode(next=head)
link = add_node
for i in range(length-n):
link = link.next
link.next = link.next.next
return add_node.next
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1e0a12c7688dfdae35250248085516c5.png)
栈法
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
add_node = ListNode(next = head)
link = add_node
q = []
while link:
q.append(link)
link = link.next
for i in range(n):
q.pop()
prev = q.pop()
prev.next = prev.next.next
return add_node.next
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8ba26f287ef72af573e72a84e4c2a4d7.png)
双指针法
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
add_node = ListNode(next = head)
fast = add_node
slow = add_node
for i in range(n+1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return add_node.next
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/be0049497f648fa7c1964f65ae31caec.png)