-
Notifications
You must be signed in to change notification settings - Fork 0
/
pile.h
135 lines (110 loc) · 2.39 KB
/
pile.h
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
131
132
133
134
/* INF3105 - Structures de données et algorithmes *
* UQAM / Département d'informatique *
* Été 2022 *
* Pile pour intérateurs ArbreAVL pour Lab7 *
* http://ericbeaudry.uqam.ca/INF3105/lab7/ */
#if !defined(__PILE__H__)
#define __PILE__H__
template <class T>
class Pile
{
public:
Pile();
Pile(const Pile&);
~Pile();
void empiler(const T&);
void depiler(T& out); // Depiler et copier le sommet dans out.
T depiler();
bool vide() const { return sommet==nullptr;}
void vider();
const Pile<T>& operator = (const Pile<T>&);
private:
//Pile(const Pile&); // on pourrait préférer mettre le constructeur par copie privé.
class Cellule
{
public:
Cellule(const T& e, Cellule* c);
T contenu;
Cellule* suivante;
};
Cellule* sommet;
};
#include "assert.h"
#include "pile.h"
template <class T>
Pile<T>::Pile()
{
sommet = nullptr;
}
template <class T>
Pile<T>::~Pile()
{
vider();
}
template <class T>
Pile<T>::Pile(const Pile<T>& autre)
{
sommet = nullptr;
// version paresseuse : il suffit d'appeler l'opéreateur =
*this = autre;
}
template <class T>
void Pile<T>::vider()
{
while(!vide())
depiler();
}
template <class T>
Pile<T>::Cellule::Cellule(const T& e, Cellule* c)
: suivante(c)
{
contenu=e;
}
template <class T>
void Pile<T>::empiler(const T& e)
{
sommet = new Cellule(e, sommet);
assert(sommet);
}
template <class T>
T Pile<T>::depiler()
{
assert(sommet);
Cellule c(*sommet);
delete sommet;
sommet = c.suivante;
return c.contenu;
}
template <class T>
void Pile<T>::depiler(T& e)
{
assert(sommet!=nullptr);
e = sommet->contenu;
Cellule* c = sommet;
sommet = sommet->suivante;
delete c;
}
template <class T>
const Pile<T>& Pile<T>::operator = (const Pile<T>& autre)
{
if(&autre == this) return *this;
Cellule** t=&sommet;
Cellule* a=autre.sommet;
while(a){
if((*t) == nullptr)
*t = new Cellule(a->contenu, nullptr);
else
(*t)->contenu = a->contenu;
t = &((*t)->suivante);
a = a->suivante;
}
a = *t;
*t = nullptr;
while(a!=nullptr){
Cellule* temp = a->suivante;
delete a;
a = temp;
}
return *this;
}
#endif