Created
September 4, 2011 07:28
-
-
Save anonymous/1192448 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(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(int v,struct Stack * const s, | |
void (*S)(struct Stack), | |
void (*F)(void)) | |
{ | |
int *tmp = malloc(sizeof(int) * (s->used + 1)); | |
if(tmp == NULL) | |
F(); | |
move(tmp,s); | |
tmp[s->used] = v; | |
++s->used; | |
s->array = tmp; | |
S(*s); | |
} | |
void top(struct Stack s, | |
void (*S)(int), | |
void (*F)(void)) | |
{ | |
if(s.used == 0) | |
F(); | |
else | |
S(s.array[s.used - 1]); | |
} | |
void pop(struct Stack *s, | |
void (*S)(int), | |
void (*F1)(void), | |
void (*F2)(void)) | |
{ | |
if(s->used == 0) | |
F1(); | |
else | |
{ | |
void cont(int v) | |
{ | |
int *tmp = malloc(sizeof(int) * (s->used - 1)); | |
if(tmp == NULL) | |
F2(); | |
--s->used; | |
move(tmp,s); | |
s->array = tmp; | |
S(v); | |
} | |
top(*s,cont,NULL); | |
} | |
} | |
void f(void) | |
{ | |
struct Stack s1;DERUARU(&s1); | |
void success(struct Stack s) | |
{ | |
print_stack(s); | |
struct Stack s2;DERUARU(&s2); | |
void success(struct Stack s) | |
{ | |
print_stack(s); | |
destruct(s1);/* s1が見える */ | |
destruct(s2); | |
} | |
void fail(void) | |
{ | |
destruct(s1);/* s1が見える */ | |
destruct(s2); | |
} | |
push(2,&s2,success,fail); | |
} | |
void fail(void) | |
{ | |
destruct(s1); | |
} | |
push(1,&s1,success,fail); | |
} | |
int main() | |
{ | |
struct Stack s;DERUARU(&s); | |
void success(struct Stack s) | |
{ | |
void success(struct Stack s) | |
{ | |
print_stack(s); | |
destruct(s); | |
exit(0); | |
} | |
void fail(void) | |
{ | |
destruct(s); | |
exit(0); | |
} | |
print_stack(s); | |
push(2,&s,success,fail); | |
print_stack(s); | |
destruct(s); | |
exit(0); | |
} | |
void fail(void) | |
{ | |
destruct(s); | |
exit(0); | |
} | |
push(1,&s,success,fail); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment