Está en la página 1de 4

EJERCICIO CON PILAS

IMPLEMENTAR TODAS LAS ACCIONES BÁSICAS DE UNA PILA

#include <iostream.h>
#include <stdlib.h>
#define STACKSIZE 100
#define FALSE 0
#define TRUE 1

struct stack
{
int top;
int items [STACKSIZE];
};
typedef struct stack *STACKPTR;

// pila vacía
int empty (STACKPTR ps);

// eliminar elementos de la pila


int pop (STACKPTR ps);

// insertar elementos de la pila


int push(STACKPTR ps, int x);

// inicializar pila
void init(STACKPTR ps):

// pila vacía
Int empty (STACKPTR ps)
{
if (ps—>top = = 1)
return TRUE;
else
return FALSE;
}

// eliminar elementos de la pila


int pop (STACKPTR ps)
{
if ( empty (ps))
{
cout << “ ∖n pila vacía “ << end;
exit (1);
}
return (ps —> items(ps—>top — ));
}
// insertar elementos a la pila
void push (STACKPTR ps, int x);
{
If (ps —>top = = STACSIZE - 1)
{
cout << “ ∖n Pila llena” << end;
exit ( 1);
}
Else
Ps—>items (++ (ps —>top)) = x;
}
// Inicializar pila
void init (STACPTR ps)
{
ps—>top = - 1;
}

NOTACION POLACA

EJEMPLO
EVALUAR UNA EXPRESIÓN ARITMETICA EN POSTFIJA
Sea la expresión aritmética:
4. 6. + 3 7. - * 5 /

#include < iostream.h >


#include < stdio.h >
#include < sodlib.h >
#include < math.h >

#define STACKSIZE 100


#define MAXIMO 80
#define FALSE 0
#define TRUE ! FALSE

struct stack
{
Int top;
float items [STACSIZE];
};
typedef struct stack *STACKPTR;

// Pila vacía
int empty (STACKPTR ps );
// eliminar elementos de la pila
float pop (STACKPTR ps);

// insertar elementos a la pila


void push (STACKPTR ps, float x);
int is_operador (char c);
float valor(float op1,float op2, char c);
float eval(char s( ) );

// programa principal
void main ( )
{
char s [MAXIMO];
cout << “ n De la cadena de caracteres de postfija :”;
gets ( s );
cout << “ valor : “ << eval ( s) << endl;;
}

int is_operador (char c)


{
char s[ ] = " + - * / ^ “;
int i = 0;
while (s ( I ) = ` 0 `;
if (c = = s [ i ++])
return TRUE
else
return FALSE,
}
float valor (float op1, float op2, char c)
{
float y;
switch (c)
{
case `+`: y = ( op1 + op2); break;
case `- `: y = (op1 - op2); break;
case `* `: y = (op1 * op2); break;
case `/ ` : y = (op1 / op2); break,
case ` ^`: y = pow (op1, op2); break;
default. break;
}
return y;
}
Int empty (STACKPTR ps)
{
If ( ps —> top = = -1)
return TRUE;
Else
return FALSE
}
float push (STACKPTR ps)
{
if (ps—>top = = [STACKSIZE -1])
{
cout << “∖n pila llena “ << end;
exit ( 1 );
}
else
Ps—>items (++ (ps —>top ) ) = x;
}
void init (STACKPTR ps)
{
ps —> top = -1;
}

// evaluar la expresión
float eval (char s ( ))
{
struct stack ps;
float op1, op2, x, y;
int i = 0;
char c;

init (&ps);
while (s ( I ) 0 ` 0 `)
{
c = s ( i ++ );
If (! is_operador (c))
{
x = c - `0 `;
push (&ps, x);
}
else
{
op2 = pop (&ps);
op1 = pop (&ps);
y = valor (op1,op2,c);
push (&ps y)
}
}
return pop (&ps);
}

También podría gustarte