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
Sort by
recency
|
683 Discussions
|
Please Login in order to post a comment
Test-case check "->next" only, not "prev". So "prev" can be leaved not updated.
PYTHON 3
def reverse(llist): if llist is None: return None
def reverse(llist): # Write your code here if not llist: return None prev, curr = None, llist while curr: temp = curr.next curr.next = prev curr.prev = temp prev = curr curr = temp return prev
Using recursion in Python :
DoublyLinkedListNode* reverse(DoublyLinkedListNode* llist) { if(llist == NULL || llist->next == NULL) return llist; DoublyLinkedListNode * cursor = llist; while(cursor->next!=NULL){ // switch prev and next pointer DoublyLinkedListNode * temp = cursor->next; cursor->next = cursor->prev; cursor->prev = temp; // move to 'next' node cursor = cursor->prev; } cursor->next = cursor->prev; cursor->prev = NULL; return cursor; }