Skip to content

Instantly share code, notes, and snippets.

Created September 4, 2011 07:27
Show Gist options
  • Save anonymous/1192446 to your computer and use it in GitHub Desktop.
Save anonymous/1192446 to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct Stack {
uint32_t used;
int *array;
};
void destruct(struct Stack s)
{
free(s.array);
}
void print_stack(const struct Stack s)
{
uint32_t i = s.used;
printf("stack length : %u\n",s.used);
printf("Top :");
for(; i != 0; --i) {
printf(" %u ",s.array[i-1]);
}
puts("");
}
void DERUARU(struct Stack *s)
{
s->used = 0;
s->array = NULL;
}
void move(int *dst,struct Stack * const s)
{
memcpy(dst,s->array,sizeof(int) * s->used);
free(s->array);
s->array = NULL;
}
void push(struct Stack * const s,int v)
{
int *tmp = malloc(sizeof(int) * (s->used + 1));
if(tmp == NULL)
return;
move(tmp,s);
tmp[s->used] = v;
++s->used;
s->array = tmp;
return;
}
int top(struct Stack s)
{
if(s.used == 0)
{
abort(); /* グワーッ!! */
}
else
return s.array[s.used - 1];
}
void pop(struct Stack * const s)
{
if(s->used == 0)
{
return;
}
else
{
int *tmp;
tmp = malloc(sizeof(int) * (s->used - 1));
if(tmp == NULL)
return;
--s->used;
move(tmp,s);
s->array = tmp;
return;
}
}
void pushloop(int i,struct Stack * const s)
{
int nouse[40000];
push(s,i);
print_stack(*s);
pushloop(i+1,s);
}
int main()
{
struct Stack s;DERUARU(&s);
print_stack(s);
push(&s,1);
print_stack(s);
pop(&s);
print_stack(s);
push(&s,2);
print_stack(s);
destruct(s);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment