Sort by

recency

|

986 Discussions

|

  • + 0 comments
    int getNode(SinglyLinkedListNode* llist, int positionFromTail) {
        // Check for edge cases: empty list or invalid position
        if (llist == nullptr || positionFromTail < 0) {
            // Return an appropriate error or special value.
            // For this example, we return a default value or handle as an error.
            // In a real-world scenario, you might throw an exception.
            return -1; 
        }
    
        auto slow = llist;
        auto fast = llist;
    
        // Move 'fast' pointer 'positionFromTail' steps ahead
        for (int i = 0; i < positionFromTail; ++i) {
            if (fast == nullptr) {
                // The position is out of bounds
                return -1;
            }
            fast = fast->next;
        }
    
        // Now, move both pointers until 'fast' reaches the end
        while (fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next;
        }
    
        return slow->data;
    }
    
  • + 0 comments

    def getNode(llist, positionFromTail): # Write your code here index = 0 result = llist current = llist

    while current:
        if index > positionFromTail:
            result = result.next
        current = current.next
        index += 1
    
    return result.data
    
  • + 0 comments

    JavaScript

    function getNode(llist, positionFromTail) {
      const values = [];
       
      let currentNode = llist;
      
      while (currentNode) {   
        values.push(currentNode.data);
        
        currentNode = currentNode.next;
      }
      
      return values.reverse()[positionFromTail];
    }
    
  • + 0 comments

    Javascript solution

    function getNode(llist, tailPos) {
        let curPos = llist
    
        while(curPos!= null){
            tailPos--
            curPos = curPos.next
        }
        
        tailPos = ((tailPos*-1) - 1)
        
        while(tailPos != 0){
            llist = llist.next
            tailPos--
        }
        return llist.data
    
    
    }
    
  • + 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