Stack
This commit is contained in:
parent
aeb01f4ee9
commit
2b6b07a3e0
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
*.out
|
||||||
|
*.o
|
||||||
70
stack.c
Normal file
70
stack.c
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
typedef struct node {
|
||||||
|
void *content;
|
||||||
|
struct node *next;
|
||||||
|
}Node;
|
||||||
|
|
||||||
|
typedef struct stack {
|
||||||
|
Node *top;
|
||||||
|
size_t w;
|
||||||
|
}Stack;
|
||||||
|
|
||||||
|
Stack *new_stack(size_t w) {
|
||||||
|
Stack *s = malloc(sizeof(Stack));
|
||||||
|
s->top = NULL;
|
||||||
|
s->w = w;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_empty(Stack *s) {
|
||||||
|
return !s->top;
|
||||||
|
}
|
||||||
|
|
||||||
|
void push(void *content, Stack *s) {
|
||||||
|
Node *n = malloc(sizeof(Node));
|
||||||
|
n->content = malloc(s->w);
|
||||||
|
mempcpy(n->content, content, s->w);
|
||||||
|
n->next = s->top;
|
||||||
|
s->top = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
void *pop(Stack *s) {
|
||||||
|
if (is_empty(s))
|
||||||
|
return NULL;
|
||||||
|
void *r = s->top->content;
|
||||||
|
Node *n = s->top;
|
||||||
|
s->top = s->top->next;
|
||||||
|
free(n);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
void destroy(Stack *s) {
|
||||||
|
while (!is_empty(s)) {
|
||||||
|
free(s->top->content);
|
||||||
|
pop(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
Stack *s = new_stack(sizeof(int));
|
||||||
|
int *a = malloc(sizeof(int));
|
||||||
|
int *b = malloc(sizeof(int));
|
||||||
|
int *c = malloc(sizeof(int));
|
||||||
|
int *d = malloc(sizeof(int));
|
||||||
|
*a=1;
|
||||||
|
*b=2;
|
||||||
|
*c=3;
|
||||||
|
*d=-1;
|
||||||
|
push(a, s);
|
||||||
|
push(b, s);
|
||||||
|
push(c, s);
|
||||||
|
push(d, s);
|
||||||
|
destroy(s);
|
||||||
|
printf("%d\n", is_empty(s));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Reference in New Issue
Block a user