Created
July 5, 2019 12:42
-
-
Save wsgac/d7d7d3b7f8a2b4f893bc40ed885dd637 to your computer and use it in GitHub Desktop.
Simple stack implementation in C
This file contains hidden or 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<stdlib.h> | |
| #include "stack.h" | |
| stack make_stack() { | |
| stack s = { | |
| (int*)malloc(BUFSIZE*sizeof(int)), | |
| BUFSIZE, | |
| 0 | |
| }; | |
| return s; | |
| } | |
| void reallocate(stack* s) { | |
| int* new_buf = (int*)malloc(s->bufsize*2); | |
| for (int i = 0; i < s->bufsize; i++) { | |
| new_buf[i] = s->buffer[i]; | |
| } | |
| free(s->buffer); | |
| s->buffer = new_buf; | |
| s->bufsize *= 2; | |
| } | |
| void push(stack* s, int el) { | |
| s->buffer[s->ptr++] = el; | |
| if (s->bufsize == s->ptr) | |
| reallocate(s); | |
| } | |
| int pop(stack* s) { | |
| return s->buffer[--s->ptr]; | |
| } | |
| int size(stack* s) { | |
| return s->ptr; | |
| } | |
| int empty(stack* s) { | |
| return size(s) == 0; | |
| } | |
| int peek(stack* s) { | |
| return s->buffer[s->ptr-1]; | |
| } |
This file contains hidden or 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
| #define BUFSIZE 4 | |
| typedef struct | |
| { | |
| int *buffer; | |
| int bufsize; | |
| int ptr; | |
| } stack; | |
| stack make_stack(); | |
| void push(stack* s, int el); | |
| int pop(stack* s); | |
| int peek(stack* s); | |
| int size(stack* s); | |
| int empty(stack* s); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment