Sort by

recency

|

969 Discussions

|

  • + 0 comments

    I see a lot of solutions posted with double loops and/or a temporary stack of values. It's quite easy to save on repeats and memory with a single pass through the list and keeping track of 2 pointers. Give the one "searching for the end" a "head start" of the amount of provided positions and when you've reached the number, update the pointer to the node with the data.

    public static int getNode(SinglyLinkedListNode llist, int positionFromTail) {
        SinglyLinkedListNode dataNode = llist;
        SinglyLinkedListNode current = llist;
        int ahead = 0;
        while (current.next != null) {
            if (ahead == positionFromTail) {
                dataNode = dataNode.next;
            } else {
                ahead++;
            }
    
            current = current.next;
        }
    
        return dataNode.data;
    }
    
  • + 0 comments

    This is Python Code using stack.

    def getNode(llist, positionFromTail):
        head = llist
        stack = []
        
        while head:
            stack.append(head.data)
            head = head.next
            
        for i in range(positionFromTail+1):
            final = stack.pop()
        
        
        return final
    
  • + 0 comments
    def getNode(llist, positionFromTail):
        len1 = 0
        temp = llist
        while temp:
            len1 += 1
            temp = temp.next
        temp = llist
        for i in range(len1 - positionFromTail - 1):
            temp = temp.next
        return temp.data
    
  • + 0 comments

    This is my solution

    let arr = []

    while(llist!= null) {
        arr.push(llist.data)
        llist = llist.next
    }
    
    while(positionFromTail > 0) {
        arr.pop()
        positionFromTail--
    }
    
    return arr[arr.length-1]
    
  • + 0 comments

    Python recursion solution explained.

    def getNode(llist, positionFromTail):
            
        def traverse(head, n=0):
            # Stop recursion condition. Stop when there is no children (reached tail)
            if head.next is None:
                return (n, head.data)
            
            # Save max_depth and possible answer value
            max_depth, ans = traverse(head.next, n+1)
            # We will exit this part only when we reach max depth of the list
            
            # As we are traversing backwards (getting outside of the recursion)
            # we check our main condition for the position from the tail
            if max_depth-positionFromTail == n:
                # If we meet the condition we return the value
                return (max_depth, head.data)
            else:
                # If the condition is not met yet or has already been met
                # we return the possible answer and the depth
                return (max_depth, ans)
        
        # Return the answer
        return traverse(llist)[1]