C/Data Structure Algorithm/Stack
A simple four-function calculator
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int *p; /* will point to a region of free memory */
int *tos; /* points to top of stack */
int *bos; /* points to bottom of stack */
void push(int i)
{
if(p > bos) {
printf("Stack Full\n");
return;
}
*p = i;
p++;
}
int pop(void)
{
p--;
if(p < tos) {
printf("Stack Underflow\n");
return 0;
}
return *p;
}
int main(void)
{
int a, b;
char s[80];
p = (int *) malloc(MAX*sizeof(int)); /* get stack memory */
if(!p) {
printf("Allocation Failure\n");
exit(1);
}
tos = p;
bos = p + MAX-1;
printf("Four Function Calculator\n");
printf("Enter "q" to quit\n");
do {
printf(": ");
gets(s);
switch(*s) {
case "+":
a = pop();
b = pop();
printf("%d\n", a+b);
push(a+b);
break;
case "-":
a = pop();
b = pop();
printf("%d\n", b-a);
push(b-a);
break;
case "*":
a = pop();
b = pop();
printf("%d\n", b*a);
push(b*a);
break;
case "/":
a = pop();
b = pop();
if(a==0) {
printf("Divide by 0.\n");
break;
}
printf("%d\n", b/a);
push(b/a);
break;
case ".": /* show contents of top of stack */
a = pop();
push(a);
printf("Current value on top of stack: %d\n", a);
break;
default:
push(atoi(s));
}
} while(*s != "q");
return 0;
}
Stack in C
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
void push(int i);
int pop(void);
int *tos, *p1, stack[SIZE];
int main(void)
{
int value;
tos = stack; /* tos points to the top of stack */
p1 = stack; /* initialize p1 */
do {
printf("Enter value: ");
scanf("%d", &value);
if(value != 0) push(value);
else printf("value on top is %d\n", pop());
} while(value != -1);
return 0;
}
void push(int i)
{
p1++;
if(p1 == (tos+SIZE)) {
printf("Stack Overflow.\n");
exit(1);
}
*p1 = i;
}
int pop(void)
{
if(p1 == tos) {
printf("Stack Underflow.\n");
exit(1);
}
p1--;
return *(p1+1);
}