Skip to content

Instantly share code, notes, and snippets.

@LeoAdamek
Created February 2, 2012 19:59
Show Gist options
  • Select an option

  • Save LeoAdamek/1725426 to your computer and use it in GitHub Desktop.

Select an option

Save LeoAdamek/1725426 to your computer and use it in GitHub Desktop.
A simple demonstration of stacks in ANSI C
/*
* stacks.c
*
* An example (and probably not great) stack implimentation in ANSI C
* Licensed under "Do what you want" by Leo Adamek (leo.adamek.me), 2012
*
* Notes:
* This program is a demonstration of stacks in C.
* The main function of this program is just a demonstration of the stack
*/
#include <stdio.h>
#include <stdlib.h>
/* Type Definition for Stack */
typedef struct{
int top;
int max_height;
float data[];
}Stack;
/* Prototype Declarations */
void push(Stack* st, float value);
float pop(Stack* st);
void init(Stack* st, int max);
int full(Stack* st);
int get_top(Stack* st);
int get_height(Stack* st);
void st_print(Stack* st);
int main(int argc, char* argv[]){
Stack s;
int i;
init(&s, 0x65536); /* Stack of maximum height 0x65536 */
st_print(&s);
push(&s, 3.14159);
push(&s, 0.6325);
push(&s, 0xD1C3);
push(&s, 0150);
st_print(&s);
printf("Top of stack is: %g\n",pop(&s));
push(&s, 0x63);
st_print(&s);
// This is an interesting one...
push(&s, pop(&s) + pop(&s));
st_print(&s);
printf("Stack Top Is: %d\n", get_top(&s) );
printf("Stack Maximum Height Is: %d\n", get_height(&s) );
printf("Emptying the stack...\n");
for(i=0;i<get_top(&s);i++){
pop(&s);
}
printf("Filling the stack (a bit)...\n");
for(i=0;i<50;i++){
push(&s, (float)0xDEADBEEF);
if(i%5 == 0){
printf("Pushed item %d\n",i);
}
}
printf("Stack Filled... (%g Items)\n",get_top(&s));
printf("Press Any Key...");
getch();
return 0;
}
/* Get current stack height and maximum height */
int get_top(Stack* st){return st->top;}
int get_height(Stack* st){return st->max_height;}
/* Add a value to the stack */
void push(Stack* st, float value){
st->data[st->top] = value;
(st->top)++;
}
/* Retreieve a value from the stack */
float pop(Stack* st){
(st->top)--;
return (st->data[st->top]);
}
/* Initialise a stack */
void init(Stack* st, int max){
st->top = 0;
st->max_height = max;
}
/* check if a stack is full */
int full(Stack* st){
return (st->top >= st->max_height);
}
/* print out a stack */
void st_print(Stack* st){
int i;
if(st->top == 0){
printf("Stack Is Empty.\n");
}else{
printf("Stack Contents:\n");
for(i=0;i<st->top;i++){
printf("%g\t",st->data[i]);
}
printf("\n\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment