Sort by

recency

|

970 Discussions

|

  • + 0 comments

    function getNode(head, positionFromTail) {

    const dict = {} let i=0 while(head){ dict[i] = head.data; i++ head=head.next } i=i-1; return dict[i-positionFromTail]

    }

  • + 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]