-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Ordered_Doubly_Linked_List.hpp
130 lines (114 loc) · 2.74 KB
/
Ordered_Doubly_Linked_List.hpp
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#ifndef LIST_H
#define LIST_H
using namespace std;
template<class T>
class List
{
class Node{
public:
friend class List<T>;
T item{};
Node* next;
Node* prev;
Node(){ next = prev = nullptr; }
Node(T& item, Node* prev, Node* next){
this->item = item;
this->prev = prev;
this->next = next;
}
};
Node* first;
Node* last;
int size;
public:
List();
~List();
bool emptyList();
void insertSingle (T& x);
void insertOrdered(T& item, int (*cmp)(const T& t1, const T& t2));
void deleteLast();
friend std::ostream& operator<< (std::ostream& out, List<T>& list){
Node *current= list.first;
while(current != nullptr){
out << current->item << endl;
current = current->next;
}
return out;
}
int size() {return size;}
};
template<class T>
List<T>::List(){
first = last = new Node();
size = 0;
}
template<class T>
List<T>::~List(){
Node* current = first;
while(first != nullptr){
first = first->next;
current->prev = current->next = nullptr;
delete current;
current = first;
}
size=0;
}
template <class T>
void List<T>::insertSingle (T& x) {
this->first=this->last=new Node(x, nullptr, nullptr);
}
template <class T>
bool List<T>::emptyList() {
return (this->size == 0);
}
template <class T>
void List<T>::insertOrdered (T& x, int (*cmp)(const T& t1, const T& t2)) {
if(emptyList()){
insertSingle(x);
this->size++;
return;
}
Node *temp = this->first;
Node* data = new Node(x, nullptr, nullptr);
while(temp!=nullptr){
if ((*cmp)(x,(temp->item))>0){
if (temp->prev==nullptr){
data->prev=nullptr;
this->first=data;
data->next=temp;
temp->prev=data;
size++;
return;
}
else{
data->next=temp;
data->prev=temp->prev;
temp->prev->next=data;
temp->prev=data;
size++;
return;
}
}
else if (temp->next==nullptr){
temp->next=data;
data->prev=temp;
data->next=nullptr;
this->last=data;
size++;
return;
}
temp=temp->next;
}
}
template <class T>
void List<T>::deleteLast () {
if (emptyList())
return;
Node *current = this->last;
Node *current1 = current->prev;
current1->next = nullptr;
delete current;
this->last = aux1;
size--;
}
#endif // LIST_H