Skip to content

Instantly share code, notes, and snippets.

@wsgac
Created July 5, 2019 12:42
Show Gist options
  • Select an option

  • Save wsgac/d7d7d3b7f8a2b4f893bc40ed885dd637 to your computer and use it in GitHub Desktop.

Select an option

Save wsgac/d7d7d3b7f8a2b4f893bc40ed885dd637 to your computer and use it in GitHub Desktop.
Simple stack implementation in C
#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];
}
#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