【leetcode刷题】19. Remove Nth Node From End of List
原题链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
解题思路:首先遍历一次得到整个list的长度;然后再从头开始计数,如果总长度为total,要删除倒数第n个,则该node与head的距离为n,找到后删除即可代码:
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
total = 0
current = head
if head.next == None:
return []
while current:
current = current.next
total += 1
i = 1
current = head
if total - n == 0:
head = head.next
while current:
if total - n == i:
follow = current.next
current.next = follow.next
# follow.next = None
break
else:
current = current.next
i += 1
return head