Part B
This commit is contained in:
@@ -26,8 +26,9 @@ void printStructure() {
|
||||
// Start iterating after the the latest entry (total_size-current_size) and continue until end (total_size)
|
||||
for(int i=total_size-current_size;i < total_size;i++) {
|
||||
// Add comma if not last (or only) slot, else add newline
|
||||
if (i + 1 != total_size) {printf("%d, ",*(ptr + i));}
|
||||
else {printf("%d\n",*(ptr + i));}
|
||||
printf((i + 1 != total_size)?"%d, ":"%d\n",*(ptr + i));
|
||||
//if (i + 1 != total_size) {printf("%d, ",*(ptr + i));}
|
||||
//else {printf("%d\n",*(ptr + i));}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
|
||||
COS135 HW9b
|
||||
Nicholas Pease
|
||||
Dynamic LIFO Stack
|
||||
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
|
||||
int ptr_size = 0;
|
||||
char* ptr;
|
||||
|
||||
void push(char addition) {
|
||||
// Deal with allocation every time push is called and pop. If not initialized, the source is NULL
|
||||
ptr = realloc((ptr_size == 0)? NULL: ptr, (ptr_size+1)*sizeof(char));
|
||||
*(ptr+ptr_size) = addition;
|
||||
ptr_size++;
|
||||
}
|
||||
|
||||
char pop() {
|
||||
char removal = *(ptr+ptr_size-1);
|
||||
ptr_size--;
|
||||
ptr = realloc((ptr_size == 0)? NULL: ptr, (ptr_size)*sizeof(char));
|
||||
return removal;
|
||||
}
|
||||
|
||||
void print() {
|
||||
for (int i = ptr_size - 1; i >= 0; i--)
|
||||
printf("%c\n",*(ptr+i));
|
||||
/*
|
||||
for (int i = 0; i < ptr_size; i++)
|
||||
printf((i + 1 != ptr_size)?"%c, ":"%c\n",*(ptr+i));
|
||||
*/
|
||||
}
|
||||
|
||||
int main() {
|
||||
char input[20] = "";
|
||||
while(strncmp("quit",input,4)!= 0) {
|
||||
printf("Enter command (push, 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, then process string for remaining integer
|
||||
if (strncmp("push",input,4) == 0) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user