class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# leetcode submit region end(Prohibit modification and deletion)
tmp, tmp.next = ListNode(None), head
pre = cur = tmp
while n:
cur = cur.next
n -= 1
while cur.next:
cur = cur.next
pre = pre.next
pre.next = pre.next.next
return tmp.next
之前错误的代码
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# leetcode submit region end(Prohibit modification and deletion)
if head.next is None:
return None
pre = cur = head
tmp = n
while n:
cur = cur.next
n -= 1
while cur.next:
cur = cur.next
pre = pre.next
pre.next = cur # 注意这一点错了,调了好长时间,这个是直接将中间的隔过去
if tmp == 1:
pre.next = None
return head
链表题技巧
- 加一个头节点 操作,返回头节点的next
- 要删除某个节点,就得知他前面的节点或者是它自身的指针。cur = cur.next
- 经常需要两个指针:或者同步指针,或者快慢指针