Sort by

recency

|

973 Discussions

|

  • + 1 comment
    def atNodeFromTail(head,position):
        cur = head
        stack = []
        while cur != None:
            stack.append(cur.data)
            cur = cur.next
        return stack[-position-1]
    

    Simple Solution with O(N) complexity

  • + 0 comments

    typescript, just recursion, not creating a stack or a dict of the visited nodes

    function traverse (llist: SinglyLinkedListNode, positionFromTail: number, found: { value: number}): number {
        if(llist.next !== null){
            const pos = 1 + traverse(llist.next, positionFromTail, found)
            if (pos === positionFromTail){
                found.value = llist.data
            }
            return pos
        }
        if (positionFromTail === 0){
            found.value = llist.data
        }
        return 0
    }
    
    function getNode(llist: SinglyLinkedListNode, positionFromTail: number): number {
        const found = {  value: 0}
        traverse(llist, positionFromTail, found)
        return found.value
    }
    
  • + 0 comments
        Stack<Integer> stack = new Stack<>();
    
    while(llist != null) {
        stack.push(llist.data);
        llist = llist.next;
    }
    
    for (int i = 0; i < positionFromTail; i++) {
        stack.pop();
    }
    
    // The top of the stack is now the desired node
    return stack.pop();
    
  • + 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;
    }