lc11~lc20

时间:2019-11-25
本文章向大家介绍lc11~lc20,主要包括lc11~lc20使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

19. 

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
class Solution:
    def removeNthFromEnd(self, head, n):
        
        head_list = []
        count = 0
        while head:
            head_list.append(head)
            head = head.next
            count = count + 1
            #print(count)
            
        if count == 1:
            return None
            
        if head_list[-n].next == None:
            head_list[-n-1].next = None
            return head_list[0]
        else:
            head_list[-n].val = head_list[-n].next.val
            head_list[-n].next = head_list[-n].next.next
            return head_list[0]

if __name__ == '__main__':
    l1 = ListNode(1)
    l1.next = l11 = ListNode(2)
    l11.next = l12 = ListNode(3)
    l12.next = l13 = ListNode(4)
    l13.next = l14 = ListNode(5)
    head = l1
    sol = Solution()
    res = sol.removeNthFromEnd(l1, 5)
    
    while res:
        print(res.val)
        res = res.next

原文地址:https://www.cnblogs.com/laojifuli/p/11925982.html