Skip to content

Instantly share code, notes, and snippets.

@xryuseix
Last active August 5, 2021 02:29
Show Gist options
  • Save xryuseix/5128dab1871ae2c3569e63493ff508ce to your computer and use it in GitHub Desktop.
Save xryuseix/5128dab1871ae2c3569e63493ff508ce to your computer and use it in GitHub Desktop.
Cでstackを作ります
#include <stdio.h>
#include <stdlib.h>
struct CharStack {
char* data;
int top; // 半開区間で終端を管理する
int max;
} typedef stack;
void push(char* data, char c, int* top) {
data[(*top)] = c;
(*top)++;
}
char pop(char* data, int* top) {
if(!(*top)) {
return -1;
}
(*top)--;
char res = *(data+(*top));
return res;
}
void print(char* data, int* top) {
for(int i = 0; i < *top; i++) {
printf("%c ", data[i]);
}
printf("\n");
}
int main(void) {
stack s;
s.max = 100;
s.top = 0;
s.data = malloc(s.max * sizeof(*s.data));
char input[100];
printf("please input: ");
scanf("%s", input);
for(int i = 0; i < strnlen(input, 100); i++) {
push(s.data, input[i], &s.top);
}
printf("pop: %c\n", pop(s.data, &s.top));
printf("pop: %c\n", pop(s.data, &s.top));
printf("pop: %c\n", pop(s.data, &s.top));
printf("please input: ");
scanf("%s", input);
for(int i = 0;i < strnlen(input, 100); i++) {
push(s.data, input[i], &s.top);
}
printf("print: ");
print(s.data, &s.top);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment