There is my answer, do I have to get the length of the List? How can I improve my code?


  • 0
    W
    # get the next node
    def getNext(x):
    	return x.next
    
    # get the size of the list
    def size(x):
    	count = 0
    	while x != None:
    		count = count + 1
    		x = getNext(x)
    	return count
    
    # the method is: get the length of the list, let n = length(list) - n, then cancel the n-th node
    
    class Solution(object):
        def removeNthFromEnd(self, head, n):
            v = head.val
            current =  head
            previous =  None
            n = size(head) - n
            while n >= 1:
                n = n - 1
                previous = current
                current =  getNext(current)
    
            if previous == None:
                head = head.next
            else:
                previous.next = current.next
            return head

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.