这是一个中等难度的问题在王道考研教材中也有提及,但是时间过得过于久远,思路已经模糊不清了,这里设置了一个头节点,将删除首元素以及其他元素的操作统一了起来,使用了双指针的技巧,解决该问题。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
Node =ListNode(None)
Node.next=head
quick,slow=Node,Node
for i in range(n):
quick=quick.next
while(quick.next!=None):
quick=quick.next
slow=slow.next
slow.next=slow.next.next
return Node.next