Created
August 30, 2022 12:40
-
-
Save Tacumi/b047c2d54ef4a47a2feedceeedaca168 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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct _stack { | |
char **m; | |
int index; | |
int limit_index; | |
int ttl; | |
int size; | |
} STACK, *pSTACK; | |
pSTACK create_stack(int size, int ttl) { | |
pSTACK p = NULL; | |
if(size < ttl) { return p; } | |
p = malloc(sizeof(STACK)); | |
p->m = (char**)malloc((sizeof(char*)) * size); | |
memset(p->m, 0, (sizeof(char*)) * size); | |
p->index = 0; | |
p->limit_index = 0; | |
p->size = size; | |
p->ttl = ttl; | |
return p; | |
} | |
int destroy_stack(pSTACK p) { | |
free(p->m); | |
p->m = NULL; | |
free(p); | |
return 0; | |
} | |
int slide_limit(pSTACK p) { | |
int index = p->index; | |
if(p->index < p->limit_index) { | |
index += p->size; | |
} | |
if((index - p->limit_index) > p->ttl) { | |
return 1; | |
} | |
return 0; | |
} | |
int push(pSTACK p, char* data) { | |
if(p->size > p->index) { | |
p->m[p->index] = data; | |
p->index = (p->index + 1) % p->size; | |
p->limit_index = (p->limit_index + slide_limit(p)) % p->size; | |
return 0; | |
} else { | |
return 1; | |
} | |
} | |
char* pop(pSTACK p) { | |
p->index--; | |
if(p->index < 0) { | |
p->index = p->size - 1; | |
} | |
return p->m[p->index]; | |
} | |
int empty(pSTACK p) { | |
return p->index == p->limit_index; | |
} | |
int main() { | |
pSTACK stack = create_stack(16, 2); | |
push(stack, "粘土を買う"); | |
push(stack, "おしごと"); | |
push(stack, "みすきー"); | |
while(!empty(stack)) { | |
printf("%s\n", pop(stack)); | |
} | |
destroy_stack(stack); | |
stack = NULL; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment