Skip to content

Instantly share code, notes, and snippets.

@MajsterTynek
Forked from anneomcl/reverse_linked_list.cpp
Last active February 25, 2017 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MajsterTynek/3dd62a1a6f29ebe7c06e30c95492be5e to your computer and use it in GitHub Desktop.
Save MajsterTynek/3dd62a1a6f29ebe7c06e30c95492be5e to your computer and use it in GitHub Desktop.
TheHappieCat: Reversing Double Linked Lists
// Example program
#include <iostream> // std::cout
#include <utility> // std::swap
using std::cout;
using std::swap;
struct Node {
int data;
Node* next;
Node* prev;
};
Node* create_node(int node_data){
Node* n = new Node();
n->data = node_data;
return n;
}
Node* push_node(Node* curr, int node_data){
if ( curr == nullptr ) return nullptr;
Node* n = create_node( node_data );
curr->next = n;
n->prev = curr;
return n;
}
Node* create_double_linked_list(int size){
if(size < 1) return nullptr;
Node* head = create_node(0);
Node* curr = head;
head->prev = nullptr;
head->next = nullptr;
for(int i = 1; i < size; i++)
curr = push_node(curr, i);
return head;
}
void print_double_linked_list(Node* head){
Node* curr = head;
if ( curr == nullptr ) return;
cout << '\n' << curr->data;
while ( curr->next )
curr = curr->next,
cout << curr->data;
cout << '\n' << curr->data;
while ( curr->prev )
curr = curr->prev,
cout << curr->data;
cout << '\n';
}
void reverse_double_linked_list(Node* & head){
// & - argument passed by reference
// That means functions is working on
// original variable given by caller.
//Your code here:
}
int main()
{
Node* head =
create_double_linked_list( 10 );
print_double_linked_list( head );
// You should see:
// 012345689 \n 9876543210
reverse_double_linked_list( head );
print_double_linked_list( head );
// You should see:
// 9876543210 \n 0123456789
// It is an example program.
// Here is no need to delete allocated memory.
return 0;
}
@MajsterTynek
Copy link
Author

My solution:

void reverse_double_linked_list(Node* & head){
    if  ( !head ) return;
    Node*& node = head;

    while( node-> next )
        swap ( node->next, node->prev ),
        node = node->prev; // next

    swap( node->next, node->prev ); // last node
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment