Sort by

recency

|

982 Discussions

|

  • + 0 comments

    My Python Soluction

    def getNode(llist, positionFromTail):
    
            prev = None
            curr = llist
            temp = curr
    
            while curr:
                    temp = curr.next
                    curr.next = prev
                    prev = curr
                    curr = temp
    
            head = prev
            curr = head
            count = 0
    
            while count < positionFromTail:
                    curr = curr.next
                    count += 1
    
            return curr.data
    
  • + 0 comments

    My Java 8 Solution

    public static int getNode(SinglyLinkedListNode llist, int positionFromTail) {
            int lenght = 0;
            SinglyLinkedListNode counterList = llist;
            
            while (counterList != null) {
                lenght++;
                counterList = counterList.next;
            }
            
            int positionFromHead = lenght - positionFromTail - 1;
            int index = 0;
            SinglyLinkedListNode node = llist;
            
            while (index < positionFromHead) {
                node = node.next;
                index++;
            }
            
            return node.data;
        }
    
  • + 0 comments
    public static int getNode(SinglyLinkedListNode head, int positionFromTail) {
        // Create two pointers, both starting at the head
        SinglyLinkedListNode fast = head;
        SinglyLinkedListNode slow = head;
    
        // Move the 'fast' pointer 'positionFromTail' steps ahead
        for (int i = 0; i < positionFromTail; i++) {
            fast = fast.next;
        }
    
        // Now move both 'fast' and 'slow' one step at a time
        // When 'fast' reaches the last node, 'slow' will be at the target node
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
    
        // 'slow' is now pointing to the node that is 'positionFromTail' from the end
        return slow.data;
    }
    
  • + 0 comments

    def getNode(llist, positionFromTail): cur = llist stack = [] while cur : stack.append(cur.data) cur = cur.next for i in range(positionFromTail+1): node_value = stack.pop() return node_value

  • + 0 comments

    simple recursive solution in linear time

        static int count = 0;
        static int val = 0;
        public static int getNode(SinglyLinkedListNode llist, int positionFromTail) {
        if(llist==null){
            count=0;
            return 0;
        }
        getNode(llist.next, positionFromTail);
        if(positionFromTail==count){
            val=llist.data;
        }
        count++;
        return val;
        }