80 lines
2.5 KiB
C
80 lines
2.5 KiB
C
/*
|
|
|
|
COS135 HW9b
|
|
Nicholas Pease
|
|
Dynamic LIFO Stack
|
|
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
// Globals
|
|
// ptr_size is number of chars in stack
|
|
// ptr is pointer to stack memory
|
|
int ptr_size = 0;
|
|
char* ptr;
|
|
|
|
// Pushes parameter addition to stack
|
|
void push(char addition) {
|
|
// Deal with allocation every time push is called and pop. If not initialized, the source is NULL to initialize
|
|
// Add one to the current size, and realloc using the extended memory
|
|
ptr = realloc((ptr_size == 0)? NULL: ptr, (ptr_size+1)*sizeof(char));
|
|
// Set the item at the new maximum position and increment the size after it is stored
|
|
*(ptr+ptr_size) = addition;
|
|
ptr_size++;
|
|
}
|
|
|
|
// Takes the last element off the stack and returns it
|
|
char pop() {
|
|
// Before data is adjusted, take the item to be removed out and store for returning later
|
|
char removal = *(ptr+ptr_size-1);
|
|
ptr_size--;
|
|
// Deal with allocation every time push is called and pop. If not initialized, the source is NULL to initialize
|
|
// Realloc the memory, effectively "deleting" the newest, now "popped"
|
|
ptr = realloc((ptr_size == 0)? NULL:ptr, (ptr_size)*sizeof(char));
|
|
return removal;
|
|
}
|
|
|
|
// Prints the entire stack
|
|
void print() {
|
|
// Starts at the end, where the start of the stack is
|
|
for (int i = ptr_size - 1; i >= 0; i--)
|
|
printf("%c\n",*(ptr+i));
|
|
}
|
|
|
|
int main() {
|
|
char input[20] = "";
|
|
// Start input menu
|
|
while(strncmp("quit",input,4)!= 0) {
|
|
printf("Enter command (push, pop, print, or quit): ");
|
|
fgets(input,20,stdin);
|
|
// Strip newline character from input (fgets)
|
|
for (int i=0;i<strlen(input);i++) if (input[i] == '\n') input[i] = '\0';
|
|
|
|
|
|
// Check if the first 4 letter of string are push
|
|
if (strncmp("push",input,4) == 0) {
|
|
// Test for maximum
|
|
if (ptr_size != 10) {
|
|
// Extract char from push. Should be slot 5
|
|
char temp = input[5];
|
|
push(temp);
|
|
} else {
|
|
printf("Error: Maximum elements in the stack\n");
|
|
}
|
|
}
|
|
// Check if the first 3 letters of the string are pop
|
|
if (strncmp("pop",input,3) == 0)
|
|
printf("Popped: %c \n",pop());
|
|
|
|
// If the first 5 letters of the input are "print", simply call printStructure() which requires no data input
|
|
if (strncmp("print",input,5) == 0 && ptr_size > 0)
|
|
print();
|
|
}
|
|
// Freeup memory and leave
|
|
printf("Bye\n");
|
|
free(ptr);
|
|
return 0;
|
|
} |