难度: Medium
原题连接
内容描述
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
思路 1 - 时间复杂度: O(N^2) - 空间复杂度: O(N)
用一个list放我们最后的n个点,初始化list的size为n+1,然后我们每次都append新的node到最后,同时pop掉最前面的node,那么这样会有两种情况
- 如果我们要删除的是head本身,那么list肯定装不满,list[0]肯定是初始化没变,此时直接返回head.next,也就是dummy
- 如果我们要删除的不是head本身,那么list肯定是满的,list[1]就是我们要删除的点
- 所以令lst[0].next = lst[2],然后返回dummy
- 但是如果n等于1的话,即我们要删除的最后一个节点的话,我们的list的长度是2,那么lst[2]就不存在了,上面的式子就是错的,此时我们直接令lst[0].next = None,这样就删掉了最后一个节点,然后直接返回dummy
但是这个方法确实繁琐,而且不管是时间还是空间都不好
我只是记录一下我的某一个想法而已,说不定这个思路可以用到别的题目上
beats 98.91%
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy, lst = head, [0] * (n+1)
idx = 0
while head:
lst = lst[1:]
lst.append(head)
head = head.next
if lst[0]: # 删除的不是head
if n == 1: # 删除最后的节点
lst[0].next = None
return dummy
lst[0].next = lst[2]
return dummy
else: # 删除head,因为删除的是head那么lst装不满
return dummy.next思路 2 - 时间复杂度: O(N) - 空间复杂度: O(1)
beats 98.91%
技巧 dummy head 和双指针。
fast先走n步,到了末尾就把slow指针跳过下一个即可。
切记最后要返回dummy.next而不是head,因为可能删的就是head,例如:
输入链表为[1], n = 1, 应该返回None而不是[1]
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
slow = fast = dummy = ListNode(-1)
dummy.next = head
for i in range(n):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next Could you do this in one pass?
思路 1 - 时间复杂度: O(N) - 空间复杂度: O(1)
把刚才的for loop放到while 里面来实现
beats 98.91%
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
slow = fast = dummy = ListNode(-1)
dummy.next = head
count = 0
while fast.next:
if count < n:
count += 1
fast= fast.next
else:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next