Skip to content

Instantly share code, notes, and snippets.

@yaotti
Created March 30, 2009 11:06
Show Gist options
  • Save yaotti/87740 to your computer and use it in GitHub Desktop.
Save yaotti/87740 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define STACKSIZE 256
typedef struct {
int *nums;
size_t len;
} mystack_t;
mystack_t *newStack(int i);
void push(mystack_t *s, int i);
int pop(mystack_t *s);
void displayStack(mystack_t *s);
void deleteStack(mystack_t *s);
int main(int argc, char **argv)
{
mystack_t *s = newStack(0);
displayStack(s);
push(s, 1);
displayStack(s);
push(s, 2);
displayStack(s);
push(s, 3);
displayStack(s);
printf("%d\n", pop(s));
displayStack(s);
printf("%d\n", pop(s));
displayStack(s);
printf("%d\n", pop(s));
displayStack(s);
printf("%d\n", pop(s));
displayStack(s);
printf("%d\n", pop(s));
displayStack(s);
push(s, 1);
displayStack(s);
deleteStack(s);
return 0;
}
mystack_t *newStack(int i)
{
mystack_t *s = (mystack_t *)malloc(sizeof(mystack_t));
s->nums = (int *)malloc(sizeof(int)*STACKSIZE);
s->len = 1;
s->nums[s->len] = i;
return s;
}
void push(mystack_t *s, int i)
{
printf(">push\n");
s->nums[(s->len)++] = i;
}
int pop(mystack_t *s)
{
printf(">pop\n");
if ((int)s->len > 0) {
return s->nums[--(s->len)];
}else {
printf("Stack has no content.\n");
return 0;
}
}
void displayStack(mystack_t *s)
{
int i;
printf("[ ");
for (i = 0; i < (int)s->len; i++) {
printf("%d ", s->nums[i]);
}
printf("]\n");
}
void deleteStack(mystack_t *s)
{
free(s->nums);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment