Ejemplos de Estructuras de Datos (Data structures examples)
description
Transcript of Ejemplos de Estructuras de Datos (Data structures examples)
Stacks
template<class DataType>struct _stack{
int size;DataType data[STACKSIZE];
};
template<class DataType>struct _stack<DataType> *_createStack(struct _stack<DataType> *ptr){
ptr = new struct _stack<DataType>;ptr->size = -1;return ptr;
}
template<class DataType>void _push(struct _stack<DataType> *ptr, DataType dato){
if(ptr->size == (STACKSIZE - 1))cout << endl << "Error: StackOverflow" << endl;
elseptr->data[++ptr->size] = dato;
}
template<class DataType>DataType _pop(struct _stack<DataType> *ptr){
if(ptr->size == -1)cout << endl << "The Stack is empty" << endl;
elsereturn ptr->data[ptr->size--];
}
template<class DataType>DataType _checkTop(struct _stack<DataType> *ptr){
if(ptr->size == -1)cout << endl << "The Stack is empty" << endl;else
return ptr->data[ptr->size];}
template<class DataType>bool _stackFull(struct _stack<DataType> *ptr){
if(ptr->size == (STACKSIZE - 1))return true;
elsereturn false;
}
template<class DataType>bool _stackEmpty(struct _stack<DataType> *ptr){
if(ptr->size == -1)return true;
elsereturn false;
}
Queues
template<class DataType>struct _queue{
int front, rear, elements;DataType data[QUEUESIZE];
};
template<class DataType>struct _queue<DataType> *_createQueue(struct _queue<DataType> *ptr){
ptr = new struct _queue<DataType>;ptr->front = (QUEUESIZE - 1);ptr->rear = (QUEUESIZE - 1);ptr->elements = 0;return ptr;
}
template<class DataType>bool _queueEmpty(struct _queue<DataType> *ptr){
return (ptr->front == ptr->rear);}
template<class DataType>bool _queueFull(struct _queue<DataType> *ptr){
return ((ptr->rear + 1) % QUEUESIZE == ptr->front);}
template<class DataType>void _enqueue(struct _queue<DataType> *ptr, DataTypedato){
if((ptr->rear + 1) % QUEUESIZE == ptr->front)cout << "Error: Full Queue" << endl;
else{ptr->rear = ((ptr->rear + 1) % QUEUESIZE);ptr->data[ptr->rear] = dato;ptr->elements++;
}}
template<class DataType>DataType _dequeue(struct _queue<DataType> *ptr){
if(ptr->front == ptr->rear)cout << "Error: Empty Queue" << endl;
else{ptr->front = ((ptr->front +1) % QUEUESIZE);ptr->elements--;return ptr->data[ptr->front];
}}
template<class DataType>int _numberElements(struct _queue<DataType> *ptr){
return ptr->elements;}
Linked Listtypedef struct _node{
int data;node *next;
}node;
void _insAfter(node *ptr, int dato){if(ptr == NULL){
ptr = new node;ptr->data = dato;ptr->next = NULL;
}else{
node *newNode = new node;newNode->next = ptr->next;ptr->next = newNode;
}}
bool _delAfter(node *ptr, int *num){if(ptr == NULL || ptr->next == NULL)
return false;else{
node *aux;aux = ptr->next;*num = aux->data;ptr->next = aux->next;delete aux;return true;
}}
AVL Tree
typedef struct _avlNode{int data;int height;_avlNode *right;_avlNode *left;
}node;
node *_newNode(node *ptr, int dato){ptr = new node;ptr->data = dato;ptr->height = 1;ptr->right = NULL;ptr->left = NULL;return ptr;
}
int _height(node *ptr){if(ptr == NULL)
return -1;else
return ptr->height;}
void _refreshHeight(node *ptr){if(ptr != NULL)
( _height(ptr->right) >= _height(ptr->left) ) ? (ptr->height = _height(ptr->right) + 1) : (ptr->height = _height(ptr->left) + 1);}
AVL Treevoid _insNode(node **root, int dato){if(*root == NULL){
*root = _newNode(*root, dato);}else{
if(dato > (*root)->data)_insNode(&(*root)->right, dato);
elseif(dato < (*root)->data)
_insNode(&(*root)->left, dato);}_refreshHeight(*root);if(_factor(*root) == -2){ //Rotate to Right
if(_factor((*root)->left) == -1)_singleRotateRight(&(*root));
else_doubleRotateRight(&(*root));
}else{
if(_factor(*root) == 2){//Rotate to Leftif(_factor((*root)->right) == 1)
_singleRotateLeft(&(*root));else
_doubleRotateLeft(&(*root));}
}}
void _doubleRotateRight(node **ptr){_singleRotateLeft(&((*ptr)->left));_singleRotateRight(ptr);
}
void _doubleRotateLeft(node **ptr){_singleRotateRight(&((*ptr)->right));_singleRotateLeft(ptr);
}
void _killTree(node *root){if(root != NULL){
_killTree(root->left);_killTree(root->right);cout << endl << "Node: " << root->data << "
killed.";delete root;root = NULL;
}}
void _singleRotateLeft(node **ptr){if(*ptr != NULL){
node *aux;aux = (*ptr)->right;(*ptr)->right = aux->left;aux->left = *ptr;_refreshHeight(*ptr);_refreshHeight(aux);*ptr = aux;
}}
void _singleRotateRight(node **ptr){if(*ptr != NULL){
node *aux;aux = (*ptr)->left;(*ptr)->left = aux->right;aux->right = *ptr;_refreshHeight(*ptr);_refreshHeight(aux);*ptr = aux;
}}
int _factor(node *ptr){if(ptr != NULL)
return _height(ptr->right) - _height(ptr->left);else
return 0;}
AVL Tree
//Definicion de la estructuratypedef struct _heap{
int datos[heapSize];}Heap;
//Asignacion de memoriaHeap * _newHeap( Heap *ptr ){
ptr = new Heap;ptr->datos[0] = 0;return ptr;
}
//Inserta un dato al final del arbolbool _insData( Heap *ptr, int dato ){
ptr->datos[0]++;if( ptr->datos[0] == heapSize ){
ptr->datos[0]--;return false;
}else{
if( ptr->datos[0] < heapSize ){ptr->datos[ ptr->datos[0] ] = dato;return true;
}else
return false;}
}
//Borra el dato que se encuentra en la raizbool _delData( Heap *ptr, int *aux ){
if( ptr->datos[0] > 0 ){*aux = ptr->datos[1];ptr->datos[1] = ptr->datos[ ptr->datos[0] ];ptr->datos[0]--;return true;
}else
return false;}
Heaps
//Reordena el arbol de arriba hacia abajovoid _fixDown( Heap *ptr ){
int i = 1, aux = 0;
while( i < ptr->datos[0] ){ //Mientras el indice i no sea igual al tamaño del arregloif( ptr->datos[0] >= (2*i + 1) ){ //Si el tamaño del arreglo es mayor que 2*i + 1, osea que si es posible que exista un hijo
derechoif( ( ptr->datos[i] < ptr->datos[2*i] ) || ( ptr->datos[i] < ptr->datos[2*i +1] ) ){ // Si alguno de los dos hijos es mayor
if( ptr->datos[2*i] > ptr->datos[2*i + 1] ){ //Cambia el dato de lugar con su hijo izquierdo
aux = ptr->datos[i];ptr->datos[i] = ptr->datos[2*i];ptr->datos[2*i] = aux;i = 2*i;
}else{//Cambia el dato de lugar con su hijo derecho
aux = ptr->datos[i];ptr->datos[i] = ptr->datos[2*i + 1];ptr->datos[2*i + 1] = aux;i = (2*i + 1);
}}else
i = ptr->datos[0]; // Cambia la condicion para que no se siga ejecutando el ciclo ya que no hay elementos más grandes debajo de este nivel
}else{ //No hay hijos derechos
if( ptr->datos[0] == 2*i ){ //Hay hijo izquierdo -- CANDIDATA A DESAPARECERaux = ptr->datos[i];ptr->datos[i] = ptr->datos[2*i];ptr->datos[2*i] = aux;i = 2*i;
}else
i = ptr->datos[0]; // Cambia la condicion para que no se siga ejecutando el ciclo ya que no hay elementos más grandes debajo de este nivel -- CANDIDATA A DESAPARECER
}}
}
Heaps
//Reordena el arbol de abajo hacia arribavoid _fixUp( Heap *ptr ){
int aux = 0, i = 0;i = ptr->datos[0];while( i > 1 ){
if( (int)(i/2) > 0 ){if( ptr->datos[i] > ptr->datos[ (int)(i/2) ]){
aux = ptr->datos[i];ptr->datos[i] = ptr->datos[ (int)(i/2) ];ptr->datos[ (int)(i/2) ] = aux;i = (int)(i/2);
}else
i = 1;}
}}
//Insercion y ordenamientovoid _siftUp( Heap *ptrHeap, int newNumber ){
if(_insData( ptrHeap, newNumber ))_fixUp( ptrHeap );
elsecout << endl << "Fallo la introducción del dato" << endl;
}
//Eliminacion y reordenamientovoid _siftDown( Heap *ptrHeap, int *saveNumber ){
if(_delData( ptrHeap, saveNumber ))_fixDown( ptrHeap );
elsecout << endl << "Error al eliminar el elemento" << endl;
}
//Impresion del arbolvoid _printHeap( Heap *ptrHeap ){
int i = 1;if( ptrHeap->datos[0] > 0 ){
/*cout << endl << ptrHeap->datos[1] << endl;while( i < ptrHeap->datos[0] ){
if( ptrHeap->datos[0] >= (2*i + 1) )cout << ptrHeap->datos[2*i] << " " << ptrHeap->datos[2*i + 1] << endl;
elsecout << ptrHeap->datos[2*i] << " " << endl;
}*/for(int i = 1; i <= ptrHeap->datos[0]; i++)
cout << ptrHeap->datos[i] << " ";}
}
//Impresion del arbolvoid _printHeapPlus( Heap *ptrHeap ){
int i = 1, k = 1;if( ptrHeap->datos[0] > 0 ){
for(int i = 1; i <= ptrHeap->datos[0]; i++){if( i == k ){
k *= 2;cout << endl;cout << "Nivel: " << (i / 2) + 1 << " ";
}cout << ptrHeap->datos[i] << " ";
}}
}
Heaps
typedef struct _nodo {int valor;struct _nodo *siguiente;
} tipoNodo;
typedef tipoNodo *pNodo;typedef tipoNodo *Pila;
/* Funciones con pilas: */void Push(Pila *l, int v);int Pop(Pila *l);
int main(){
Pila pila = NULL;pNodo p;
Push(&pila, 20);Push(&pila, 10);Push(&pila, 40);Push(&pila, 30);
printf("%d, ", Pop(&pila));printf("%d, ", Pop(&pila));printf("%d, ", Pop(&pila));printf("%d\n", Pop(&pila));
system("PAUSE");return 0;
}
void Push(Pila *pila, int v){
pNodo nuevo;
/* Crear un nodo nuevo */nuevo = (pNodo)malloc(sizeof(tipoNodo));nuevo->valor = v;
/* Añadimos la pila a continuación del nuevo nodo */nuevo->siguiente = *pila;/* Ahora, el comienzo de nuestra pila es en nuevo nodo */*pila = nuevo;
}
int Pop(Pila *pila){
pNodo nodo; /* variable auxiliar para manipular nodo */int v; /* variable auxiliar para retorno */
/* Nodo apunta al primer elemento de la pila */nodo = *pila;if(!nodo) return 0; /* Si no hay nodos en la pila retornamos 0 *//* Asignamos a pila toda la pila menos el primer elemento */*pila = nodo->siguiente;/* Guardamos el valor de retorno */v = nodo->valor; /* Borrar el nodo */free(nodo);return v;
}
Dynamic Stack
typedef struct _nodo {int valor;struct _nodo *siguiente;
} tipoNodo;
typedef tipoNodo *pNodo;
/* Funciones con colas: */void Anadir(pNodo *primero, pNodo *ultimo, int v);int Leer(pNodo *primero, pNodo *ultimo);
int main(){
pNodo primero = NULL, ultimo = NULL;
Anadir(&primero, &ultimo, 20);printf("Añadir(20)\n");Anadir(&primero, &ultimo, 10);printf("Añadir(10)\n");printf("Leer: %d\n", Leer(&primero, &ultimo));Anadir(&primero, &ultimo, 40);printf("Añadir(40)\n");Anadir(&primero, &ultimo, 30);printf("Añadir(30)\n");printf("Leer: %d\n", Leer(&primero, &ultimo));printf("Leer: %d\n", Leer(&primero, &ultimo));Anadir(&primero, &ultimo, 90);printf("Añadir(90)\n");printf("Leer: %d\n", Leer(&primero, &ultimo));printf("Leer: %d\n", Leer(&primero, &ultimo));
system("PAUSE");return 0;
}
void Anadir(pNodo *primero, pNodo *ultimo, int v){
pNodo nuevo;
/* Crear un nodo nuevo */nuevo = (pNodo)malloc(sizeof(tipoNodo));nuevo->valor = v;/* Este será el último nodo, no debe tener siguiente */nuevo->siguiente = NULL;/* Si la cola no estaba vacía, añadimos el nuevo a continuación de ultimo */if(*ultimo) (*ultimo)->siguiente = nuevo;/* Ahora, el último elemento de la cola es el nuevo nodo */*ultimo = nuevo;/* Si primero es NULL, la cola estaba vacía, ahora primero apuntará también al nuevo nodo */if(!*primero) *primero = nuevo;
}
int Leer(pNodo *primero, pNodo *ultimo){
pNodo nodo; /* variable auxiliar para manipular nodo */int v; /* variable auxiliar para retorno */
/* Nodo apunta al primer elemento de la pila */nodo = *primero;if(!nodo) return 0; /* Si no hay nodos en la pila retornamos 0 *//* Asignamos a primero la dirección del segundo nodo */*primero = nodo->siguiente;/* Guardamos el valor de retorno */v = nodo->valor; /* Borrar el nodo */free(nodo);/* Si la cola quedó vacía, ultimo debe ser NULL también*/if(!*primero) *ultimo = NULL;return v;
}Dynamic Queues
typedef struct _nodo {int valor;struct _nodo *siguiente;
} tipoNodo;
typedef tipoNodo *pNodo;typedef tipoNodo *Lista;
// Funciones con listas:void Insertar(Lista *l, int v);void Borrar(Lista *l, int v);void BorrarLista(Lista *);void MostrarLista(Lista l);
void Insertar(Lista *lista, int v){
pNodo nodo;
// Creamos un nodo para el nuvo valor a insertarnodo = (pNodo)malloc(sizeof(tipoNodo));nodo->valor = v;
// Si la lista está vacía, la lista será el nuevo nodo// Si no lo está, insertamos el nuevo nodo a continuación del apuntado// por listaif(*lista == NULL) *lista = nodo;else nodo->siguiente = (*lista)->siguiente;// En cualquier caso, cerramos la lista circular(*lista)->siguiente = nodo;
}
void Borrar(Lista *lista, int v){
pNodo nodo;
nodo = *lista;
// Hacer que lista apunte al nodo anterior al de valor vdo {
if((*lista)->siguiente->valor != v) *lista = (*lista)->siguiente;} while((*lista)->siguiente->valor != v && *lista != nodo);// Si existe un nodo con el valor v:if((*lista)->siguiente->valor == v) {
// Y si la lista sólo tiene un nodoif(*lista == (*lista)->siguiente) {
// Borrar toda la listafree(*lista);*lista = NULL;
}else {
// Si la lista tiene más de un nodo, borrar el nodo de valor vnodo = (*lista)->siguiente;(*lista)->siguiente = nodo->siguiente;free(nodo);
}}
}
Lista Circular
void BorrarLista(Lista *lista){
pNodo nodo;
// Mientras la lista tenga más de un nodowhile((*lista)->siguiente != *lista) {
// Borrar el nodo siguiente al apuntado por listanodo = (*lista)->siguiente;(*lista)->siguiente = nodo->siguiente;free(nodo);
}// Y borrar el último nodofree(*lista);*lista = NULL;
}
void MostrarLista(Lista lista){
pNodo nodo = lista;
do {printf("%d -> ", nodo->valor);nodo = nodo->siguiente;
} while(nodo != lista);printf("\n");
}
Lista Circular