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.
Reverse a doubly linked list
Reverse a doubly linked list
+ 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; }
+ 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); }
+ 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
+ 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; }
+ 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.
Load more conversations
Sort 604 Discussions, By:
Please Login in order to post a comment