#include "SLStack.h"
#include <stdlib.h>
#include <stdio.h>
// ULTIMO EN ENTRAR, PRIMERO EN SALIR.
// Yo tengo que saber siempre quien es la cabeza.
struct _SLStackNode *head = NULL;
int astack_top (){
return head->data;
}
// Toma una pila y un elemento y agrega el elemento a la pila.
void astack_push (int data){
/*
Si yo quiero agregar un elemento a la pila, debo cambiar adonde apunta la cabeza.
*/
struct _SLStackNode *newNode = malloc (sizeof(struct _SLStackNode));
newNode->data = data;
newNode->next = head;
head=newNode;
}
int astack_pop (){
/* El elemento anterior de la cabeza, pasa a ser el
*/
struct _SLStackNode *nodeToDelete = head;
int v = nodeToDelete->data;
head=head->next;
free(nodeToDelete);
return v;
}
void astack_destroy (){
struct _SLStackNode *nodeToDelete;
while (head != NULL){
nodeToDelete=head;
free(nodeToDelete);
head=head->next;
}
}
void astack_reverse (){
int size=5;
int *pila = malloc (sizeof (int)*size);
int n_elems=0;
int i;
// Guardo todos los datos en un arreglo.
while (head != NULL){
if (n_elems != size){
pila[n_elems++] = head->data;
head = head->next;
}else{
// ... Si se queda sin memoria
size+=2;
pila = realloc (pila, size*sizeof(int));
pila[n_elems++] = head->data;
head = head->next;
}
}
// Chau pila actual.
astack_destroy();
// Construyo la pila devuelta. Del Ășltimo al primero.
for (i=0; i<n_elems; i++)astack_push(pila[i]);
free(pila);
}
void astack_print (){
struct _SLStackNode *mostrar = head;
while (mostrar != NULL){
printf ("%d ",mostrar->data);
mostrar=mostrar->next;
}
}