Skip to content

Instantly share code, notes, and snippets.

@NicolaBernini
Created January 15, 2021 12:18
Show Gist options
  • Save NicolaBernini/c645b39004a75539035b3718f019409a to your computer and use it in GitHub Desktop.
Save NicolaBernini/c645b39004a75539035b3718f019409a to your computer and use it in GitHub Desktop.
Solution to Reverse a doubly linked list
#include <bits/stdc++.h>
using namespace std;
class DoublyLinkedListNode {
public:
int data;
DoublyLinkedListNode *next;
DoublyLinkedListNode *prev;
DoublyLinkedListNode(int node_data) {
this->data = node_data;
this->next = nullptr;
this->prev = nullptr;
}
};
class DoublyLinkedList {
public:
DoublyLinkedListNode *head;
DoublyLinkedListNode *tail;
DoublyLinkedList() {
this->head = nullptr;
this->tail = nullptr;
}
void insert_node(int node_data) {
DoublyLinkedListNode* node = new DoublyLinkedListNode(node_data);
if (!this->head) {
this->head = node;
} else {
this->tail->next = node;
node->prev = this->tail;
}
this->tail = node;
}
};
void print_doubly_linked_list(DoublyLinkedListNode* node, string sep, ofstream& fout) {
while (node) {
fout << node->data;
node = node->next;
if (node) {
fout << sep;
}
}
}
void free_doubly_linked_list(DoublyLinkedListNode* node) {
while (node) {
DoublyLinkedListNode* temp = node;
node = node->next;
free(temp);
}
}
// Complete the reverse function below.
/*
* For your reference:
*
* DoublyLinkedListNode {
* int data;
* DoublyLinkedListNode* next;
* DoublyLinkedListNode* prev;
* };
*
*/
DoublyLinkedListNode* reverse(DoublyLinkedListNode* head) {
auto temp = head;
while(head != nullptr)
{
temp = head->next;
head->next = head->prev;
head->prev = temp;
if(temp==nullptr) return head;
head=temp;
}
return head;
}
int main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment