-
Notifications
You must be signed in to change notification settings - Fork 0
/
tut40.cpp
80 lines (70 loc) · 1.57 KB
/
tut40.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
using namespace std;
class DoublyLL{
public:
int data;
DoublyLL* next;
DoublyLL* prev;
DoublyLL(int d){
this->data = d;
this->next = NULL;
this->prev = NULL;
}
~DoublyLL(){
if(this->next!=NULL){
delete next;
this->next = NULL;
}
}
};
void printDLL(DoublyLL* head){
DoublyLL* temp = head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<" Head = "<<head->data<<" "<<endl;
}
void insertAtHead(DoublyLL* &tail, DoublyLL* &head, int d) {
//empty list
if(head == NULL) {
DoublyLL* temp = new DoublyLL(d);
head = temp;
tail = temp;
}
else{
DoublyLL* temp = new DoublyLL(d);
temp -> next = head;
head -> prev = temp;
head = temp;
}
}
DoublyLL* reverseLL(DoublyLL* head){
DoublyLL* back = NULL;
DoublyLL* cur = head;
DoublyLL* forward = NULL;
while(cur != NULL){
forward = cur->next;
cur->next = back;
cur->prev = forward;
back = cur;
cur = forward;
}
return back;
}
int main(){
DoublyLL* node1 = new DoublyLL(7);
DoublyLL* head = node1;
DoublyLL* tail = node1;
printDLL(head);
insertAtHead(tail, head, 6);
insertAtHead(tail, head, 5);
insertAtHead(tail, head, 4);
insertAtHead(tail, head, 3);
insertAtHead(tail, head, 2);
insertAtHead(tail, head, 1);
printDLL(head);
head = reverseLL(head);
printDLL(head);
return 0;
}