Sort by

recency

|

981 Discussions

|

  • + 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;
        }
    
  • + 0 comments

    My Java solution with linear time complexity and constant space complexity:

    public static int getNode(SinglyLinkedListNode llist, int positionFromTail) {
            int length = getLength(llist);
            int position = (length - 1) - positionFromTail;
            for(int i = 0; i < position; i++){
                llist = llist.next;
            }
            return llist.data;
        }
        
        public static int getLength(SinglyLinkedListNode llist){
            int length = 0;
            while(llist != null){
                length++;
                llist = llist.next;
            }
            return length;
        }