Created
October 13, 2017 01:58
-
-
Save estebanz01/06a17cbbccd2c17430757abc33dabed0 to your computer and use it in GitHub Desktop.
Colas en C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Example program | |
| #include <iostream> | |
| #include <string> | |
| using namespace std; | |
| class Elemento { | |
| public: | |
| int dato; | |
| Elemento* siguiente; | |
| Elemento(): dato(0), siguiente(NULL) {} // Valor por default, cero. | |
| }; | |
| class Cola { | |
| public: | |
| Elemento* tope; | |
| Elemento* cola; | |
| int total; | |
| int elementos_existentes = 0; | |
| Cola(): tope(NULL), cola(NULL), total(0) {} | |
| Cola(int n) { | |
| this->tope = NULL; | |
| this->cola = NULL; | |
| this->total = n; | |
| } | |
| Elemento* pop() { | |
| if(this->elementos_existentes > 0) { | |
| Elemento* sacarme = this->tope; | |
| this->tope = sacarme->siguiente; | |
| this->elementos_existentes -= 1; | |
| return sacarme; | |
| } else { | |
| cout << "Nada para sacar" << endl; | |
| return NULL; | |
| } | |
| } | |
| void push(Elemento* nuevo) { | |
| if(this->total >= this->elementos_existentes) { | |
| if(this->elementos_existentes == 0) { | |
| this->tope = this->cola = nuevo; | |
| } else { | |
| this->cola->siguiente = nuevo; | |
| this->cola = nuevo; | |
| } | |
| this->elementos_existentes += 1; | |
| } else { | |
| cout << "Error! cola llena" << endl; | |
| } | |
| } | |
| }; | |
| int main() { | |
| Cola* stack = new Cola(); | |
| stack->total = 15; | |
| cout << "Llenando la cola" << endl; | |
| for(int i = 0; i < 17; i++) { | |
| Elemento* node = new Elemento(); | |
| node->dato = i+1; | |
| cout << "tratando de insertar " << i+1 << endl; | |
| stack->push(node); | |
| } | |
| cout << "Vaciando cola" << endl; | |
| Elemento * c = stack->pop(); | |
| while(c != NULL) { | |
| cout << c->dato << endl; | |
| c = stack->pop(); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment