3/11/08

Stack Implementation in C

This is a simple stack implemented in C. It's not dynamic but can easy modified to be.
It is just one static table of integer and user can push and pop integers. If you want to make it a dynamic stack you just have to malloc() when push() and realloc() when pop(). You may double the size when push and when items in stack are less than the half size of the stack realloc(). Furthermore you may store in stack void* which mean you can save anything in the stack.
Here is the source code of a simple stack of integers.

#include <stdio.h>
#define N 15

int table[N];int pos;
void stackinit() {
pos=0;
}

int stackempty() {
if (pos!=0) {return(1);}
return(0);
}

int stackenter(int num) {
if(pos==N) {return(0);}
else{
table[pos]=num;
pos++;
return(1);
}
}

int stackget() {
int get;
pos--;
get=table[pos];
return(get);
}

int main(int argc,char*argv[]) {
int sel,num;
stackinit();
do {
putchar('\n');
printf(" 0 : Exit\n");
printf(" 1 : Push\n");
printf(" 2 : Pop\n");
printf(" Choose one of the above options: ");
scanf("%d",&sel);
switch (sel) {
case 1 : {
printf("Give number : ");
scanf("%d",&num);
if (stackenter(num)) {
printf(" Push successful\n");
}
else {
printf(" Stack is full\n");
}
break;
}
case 2 : {
if(stackempty()) {
printf(" Next number is : %d\n",stackget());
}
else {
printf(" Empty stack\n");
}
break;
}
}
}
while(sel!=0);
}

No comments: