-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTAREA2_PilaInvertida.CPP
More file actions
74 lines (67 loc) · 1.6 KB
/
TAREA2_PilaInvertida.CPP
File metadata and controls
74 lines (67 loc) · 1.6 KB
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
#include <iostream>
using namespace std;
//class node
template<class T>
class Node {
public:
T data;
Node<T>* next;
Node(T data) : data(data), next(nullptr) {}
};
//class stack
template<class T>
class Stack {
private:
Node<T>* top;
public:
Stack() : top(nullptr) {}
void push(T data) {
Node<T>* newNode = new Node<T>(data);
newNode->next = top;
top = newNode;
}
T pop() {
if (!isEmpty()) {
Node <T>* temp = top;
T data = top->data;
top = top->next;
delete temp;
return data;
}
// throw para evitar output infinito
throw runtime_error("La pila esta vacia");
}
bool isEmpty() {
return top == NULL;
}
void print() {
Node <T>* current = top;
while (current != NULL) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
//funcion invertir pila
void invertirPila() {
Stack<T> tempStack;
while (!isEmpty()) {
tempStack.push(pop());
}
top = tempStack.top; // Point top to the reversed stack
}
};
int main () {
Stack<int> pila;
pila.push(1);
pila.push(2);
pila.push(3);
pila.push(4);
pila.push(5);
cout<<"pila original: ";
pila.print();
pila.invertirPila();
cout<<"pila invertida: ";
pila.print();
return 0;
}