Skip to content

Instantly share code, notes, and snippets.

@cbscribe
Last active November 6, 2020 18:43
Show Gist options
  • Save cbscribe/f1f0532b58b5653b861906c1433f49aa to your computer and use it in GitHub Desktop.
Save cbscribe/f1f0532b58b5653b861906c1433f49aa to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <cs50.h>
bool push(char *item);
char *pop(void);
bool is_empty(void);
bool is_full(void);
#define CAPACITY 10
typedef struct
{
char *contents[CAPACITY];
int top;
} stack;
stack s;
int main(void)
{
s.top = 0;
for (int i = 0; i < CAPACITY+1; i++)
{
push(get_string("Enter a string: "));
}
printf("Stack has %i items.\n", s.top);
for (int i = 0; i < CAPACITY; i++)
{
printf("%s\n", pop());
}
printf("Stack has %i items.\n", s.top);
printf("Full: %s\n", (is_full() ? "true" : "false"));
printf("Empty: %s\n", (is_empty() ? "true" : "false"));
}
bool push(char *item)
{
if (s.top < CAPACITY)
{
s.contents[s.top] = item;
s.top++;
return true;
}
else
{
printf("Stack is full!\n");
return false;
}
}
char *pop(void)
{
if (s.top > 0)
{
s.top--;
return s.contents[s.top];
}
else
{
printf("Stack is empty!\n");
return NULL;
}
}
bool is_empty(void)
{
return s.top == 0;
}
bool is_full(void)
{
return s.top == CAPACITY;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment