Skip to content

Instantly share code, notes, and snippets.

@cs-fedy
Last active August 6, 2020 08:43
Show Gist options
  • Save cs-fedy/dda3d0d5052df000d39643154168fcb8 to your computer and use it in GitHub Desktop.
Save cs-fedy/dda3d0d5052df000d39643154168fcb8 to your computer and use it in GitHub Desktop.
Array Implementation of STACK (abstract data type) in C programming.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct stack {
int * keys;
int max_size;
int peek;
};
// defining a new type stck of struct stack.
typedef struct stack stck;
//Function prototpye or method on stack.
stck * create_stack(int); // create_stack will initiate the stack.
unsigned is_empty(stck); // isEmpty will tells weather a stack is empty.
unsigned is_full(stck); // isFull will tells weather a stack is full.
int get_peek(stck); // Peek will return the top most element of the stack.
void push(int, stck *); // push key into the stack.
void pop(stck *); //Pop will delete the last element of the stack.
stck * create_stack(int max_size) {
stck * st;
st = malloc(sizeof(stck));
st->peek = -1;
st->max_size = max_size;
st->keys = malloc(max_size * sizeof(int));
return st;
}
unsigned is_empty(stck st) {
return st.peek == -1;
}
unsigned is_full(stck st) {
return st.peek == st.max_size -1;
}
int get_peek(stck st) {
assert(!is_empty(st));
return st.keys[st.peek];
}
void push(int key, stck * st) {
// stack overflow
assert(!is_full(*st));
st->keys[++st->peek] = key;
}
void pop(stck * st) {
// stack underflow
assert(!is_empty(*st));
st->peek--;
}
int main() {
int stack_max_size = 100, index;
stck * st = create_stack(stack_max_size);
for (index = 0; index < 10; index++) {
push(index, &st);
}
while (!is_empty(*st)) {
printf("%d -- ", get_peek(*st));
pop(&st);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment