Reverse a doubly linked list

Sort by

recency

|

45 Discussions

|

  • + 0 comments

    Java Solution:

        public static DoublyLinkedListNode reverse(DoublyLinkedListNode llist) {
            
            DoublyLinkedListNode curr = llist;
            DoublyLinkedListNode prev = null;
            
            while(curr != null){
                DoublyLinkedListNode next = curr.next;
                
                curr.next = prev;
                curr.prev = next;
                prev = curr;
                
                curr = next;
            }
        
            return prev;
        }
    
  • + 0 comments

    Here is HackerRank Reverse a doubly linked list problem solution in Python, Java, C++, C and javascript

  • + 0 comments

    Solution in C++:

    DoublyLinkedListNode* reverse(DoublyLinkedListNode* llist) {
        if (llist == nullptr) {
            return llist;
        }
        
        std::swap(llist->next, llist->prev);
        while (llist->prev != nullptr) {
            llist = llist->prev;
            std::swap(llist->next, llist->prev);
        }
        
        return llist;
    }
    
  • + 0 comments

    Solution in C:

    DoublyLinkedListNode* reverse(DoublyLinkedListNode* llist) {
        struct DoublyLinkedListNode* curr = *(&llist);
        struct DoublyLinkedListNode* prev = NULL;
        struct DoublyLinkedListNode* next;
    
        while (curr != NULL)
        {
            next = curr->next;
            curr->next = prev;
            curr->prev = next;
            prev = curr;
            curr =  next;
        }
    
        *(&llist) = prev;
        
        return *(&llist);
    }
    
  • + 0 comments

    Only one line difference from the previous task (Scala):

        def reverse(llist: DoublyLinkedListNode): DoublyLinkedListNode = {
          def reverseNode(node: DoublyLinkedListNode, next: DoublyLinkedListNode): DoublyLinkedListNode =
            if (node == null) next
            else {
              val prev = node.next
              node.prev = prev
              node.next = next
              reverseNode(prev, node)
            }
          
          reverseNode(llist, null)
        }