We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Data Structures
  3. Linked Lists
  4. Reverse a doubly linked list
  5. Discussions

Reverse a doubly linked list

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 604 Discussions, By:

votes

Please Login in order to post a comment

  • zqcathy0_0
    7 years ago+ 12 comments

    Share my non-recursive Java solution

    Node Reverse(Node head) {
        Node temp = head;
        Node newHead = head;
        while (temp != null) {
            Node prev = temp.prev;
            temp.prev = temp.next;
            temp.next = prev;
            newHead = temp;
            temp = temp.prev;
        }
        return newHead;
    }
    
    70|
    Permalink
    View more Comments..
  • bhoeting
    7 years ago+ 5 comments

    Thought I'd share my recursive solution:

    Node* Reverse(Node* node)
    {
      // If empty list, return
      if (!node) return NULL;
      
      // Otherwise, swap the next and prev
      Node *temp = node->next;
      node->next = node->prev;
      node->prev = temp;
      
      // If the prev is now NULL, the list
      // has been fully reversed
      if (!node->prev) return node;
      
      // Otherwise, keep going
      return Reverse(node->prev);
    }
    
    23|
    Permalink
    View more Comments..
  • ankurk007
    5 years ago+ 3 comments

    Python3:

    def Reverse(head):
    
        curr = None
    
        while head:
    
            nxt = head.next
            curr = head
            head.next = head.prev
            head.prev = nxt
            head = nxt
        
        return curr
    
    20|
    Permalink
  • onuremreerol
    5 years ago+ 6 comments

    Here is a easy solution. If you have any question just ask. :)

    Node* Reverse(Node* head)
    {
        Node *temp;
        Node *itr = head;
        
        while (itr) {
            temp = itr->next; //reserve the next
            itr->next = itr->prev; //swap prev and next
            itr->prev = temp;
            head = itr; //we do not know if there is a next element 
            itr = temp; //iterate to next
        }
        
        return head;
    }
    
    14|
    Permalink
    View more Comments..
  • destroyer08
    8 years ago+ 4 comments

    This part was much like learn with fun ... requesting same for stack, queue, tree and other data structure. It will help me a lot.

    12|
    Permalink
    View more Comments..
Load more conversations

Need Help?


View editorial
View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature