-
-
Save MajsterTynek/3dd62a1a6f29ebe7c06e30c95492be5e to your computer and use it in GitHub Desktop.
TheHappieCat: Reversing Double Linked Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My solution: