-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeque.cpp
111 lines (105 loc) · 2.07 KB
/
deque.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
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
/**
* @file deque.cpp
* Implementation of the Deque class.
*
*/
/* Constructor for the Deque class */
template <class T>
Deque<T>::Deque(){
k1 = 0;
k2 = -1;
}
/**
* Adds the parameter object to the right of the Deque.
*
* @param newItem object to be added to the Deque.
*/
template <class T>
void Deque<T>::pushR(T const& newItem)
{
data.push_back(newItem);
k2++;
}
/**
* Removes the object at the left of the Deque, and returns it to the
* caller.
*
* See .h file for implementation notes.
*
* @return The leftmost item of the Deque.
*/
template <class T>
T Deque<T>::popL()
{
if(!isEmpty()){
T temp = data[k1];
k1++;
if(k2-k1 < data.size()/2) {
vector<T> tempVec;
for(int i = k1; i <= k2; i++){
tempVec.push_back(data[i]);
}
data = tempVec;
k2 = k2 - k1;
k1 = 0;
}
return temp;
}
}
/**
* Removes the object at the right of the Deque, and returns it to the
* caller.
*
* @return The rightmost item of the Deque.
*/
template <class T>
T Deque<T>::popR()
{
if(!isEmpty()){
T temp = data[k2];
data.pop_back();
k2--;
if(k2-k1 < data.size()/2) {
vector<T> tempVec;
for(int i = k1; i <= k2; i++){
tempVec.push_back(data[i]);
}
data = tempVec;
k2 = k2 - k1;
k1 = 0;
}
return temp;
}
}
/**
* Finds the object at the left of the Deque, and returns it to the
* caller. Unlike popL(), this operation does not alter the deque.
*
* @return The item at the left of the deque.
*/
template <class T>
T Deque<T>::peekL()
{
return data[k1];
}
/**
* Finds the object at the right of the Deque, and returns it to the
* caller. Unlike popR(), this operation does not alter the deque.
*
* @return the value of The item at the right of the deque.
*/
template <class T>
T Deque<T>::peekR()
{
return data[k2];
}
/**
* Determines if the Deque is empty.
*
* @return bool which is true if the Deque is empty, false otherwise.
*/
template <class T>
bool Deque<T>::isEmpty() const
{
return k1 > k2;
}