-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_linked_list.cpp
64 lines (58 loc) · 1.32 KB
/
doubly_linked_list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
code to reverse a doubly linked list
*/
#include <iostream>
typedef struct node
{
int data;
node *next;
node *prev;
}node;
node *make_list(int to_push[5]){
node *prev = NULL;
// dont rush. check if conditions are correct
for(int i= 4; i>=0; i--){
node *N = (node*)malloc(sizeof(node));
N->prev = NULL;
if(i != 4){
prev->prev = N; // great trick to set previous nodes :)
}
N->data = to_push[i];
N->next = prev;
prev = N;
}
return prev;
}
// Amazing code to reverse a list. Learnt a lot!
// what i did here was, swap the prev and next pointers and
// at the end of the original DLL, head pointed to NULL and temp pointed to second last element
// so setting head = temp->prev after the while loop makes head the start of the linked list!
node *reverse(node *head){
head->prev = NULL;
node *temp;
while(head != NULL){
temp = head->prev;
head->prev = head->next;
head->next = temp;
head = head->prev;
}
head = temp->prev;
return head;
}
int main(){
node *head = NULL, *travel = NULL;
int to_push[5] = {3,2,5,6,7};
head = make_list(to_push);
travel = head;
while(travel!= NULL){
std::cout << travel->data << " ";
travel = travel->next;
}
std::cout << "\nrev order is: \n";
travel = reverse(head);
while(travel!= NULL){
std::cout << travel->data << " ";
travel = travel->next;
}
return 0;
}