Leetcode19 删除链表指定节点

Leetcode19 删除链表指定节点_第1张图片

思路:用列表保存链表,然后分情况讨论。

class Solution:
    def removeNthFromEnd(self, head, n: int):
        node_list=[head]
        while head.next:
            head=head.next
            node_list.append(head)
        remove_loc=len(node_list)-n
        #要移除的位置
        if len(node_list)==1:
           return None
        if remove_loc==0:
           return node_list[0].next
        if remove_loc==len(node_list)-1:
           node_list[-2].next=None
           return node_list[0]
        else:
           node_list[remove_loc-1].next=node_list[remove_loc].next
           return node_list[0]

你可能感兴趣的:(Leetcode中等题,python,leetcode)