67 lines
1.2 KiB
C
67 lines
1.2 KiB
C
|
#include "pile.h"
|
||
|
|
||
|
#include <stdlib.h>
|
||
|
#include <stdio.h>
|
||
|
|
||
|
void init( struct Pile* p ) {
|
||
|
p->height = 0;
|
||
|
p->l = NULL;
|
||
|
}
|
||
|
|
||
|
void push( struct Pile* p, struct NumContainer i ) {
|
||
|
struct List* aux = p->l;
|
||
|
|
||
|
p->l = (struct List*)malloc(sizeof(struct List));
|
||
|
if (p->l == NULL) {
|
||
|
fprintf(stderr, "Error: Could not allocate memory for the next cell on the stack\n");
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
p->l->next = aux;
|
||
|
p->l->i = i;
|
||
|
++(p->height);
|
||
|
}
|
||
|
|
||
|
struct NumContainer top( struct Pile* p ) {
|
||
|
if ( p->height == 0 ) {
|
||
|
fprintf(stderr, "Error: The stack has no element, cannot find top\n");
|
||
|
exit(1);
|
||
|
}
|
||
|
return p->l->i;
|
||
|
}
|
||
|
|
||
|
void print( struct Pile* p ) {
|
||
|
struct List* aux = p->l;
|
||
|
|
||
|
while (aux != NULL) {
|
||
|
printNum(aux->i);
|
||
|
printf(" ");
|
||
|
aux = aux->next;
|
||
|
}
|
||
|
/* printf("NULL"); */
|
||
|
}
|
||
|
|
||
|
void pop( struct Pile* p ) {
|
||
|
struct List* aux;
|
||
|
|
||
|
if ( p->height != 0 ) {
|
||
|
--(p->height);
|
||
|
aux = p->l;
|
||
|
p->l = p->l->next;
|
||
|
free(aux);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void end( struct Pile* p ) {
|
||
|
while (p->height != 0) {
|
||
|
pop(p);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void getlastnums( struct NumContainer* i, struct NumContainer* j, struct Pile* pile ) {
|
||
|
*j = top(pile);
|
||
|
pop(pile);
|
||
|
*i = top(pile);
|
||
|
pop(pile);
|
||
|
}
|