Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions Coding/reverse_linkedlist.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
int data;
Node* next;
Node* prev;
};

void reverse(Node** head_ref)
{
Node* temp = NULL;
Node* current = *head_ref;

while (current != NULL) {
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}


if (temp != NULL)
*head_ref = temp->prev;
}


void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();

new_node->data = new_data;

new_node->prev = NULL;

new_node->next = (*head_ref);

if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;

(*head_ref) = new_node;
}


void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}

int main()
{
Node* head = NULL;

push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);

cout << "Original Linked list" << endl;
printList(head);

reverse(&head);

cout << "\nReversed Linked list" << endl;
printList(head);

return 0;
}