From ab10a3b68a9d0717178741f722c25eabf4240300 Mon Sep 17 00:00:00 2001 From: Abigail Date: Tue, 12 Jan 2021 00:51:09 +0100 Subject: C solution for week 95/part 2. --- challenge-095/abigail/README.md | 1 + challenge-095/abigail/c/ch-2.c | 85 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 challenge-095/abigail/c/ch-2.c diff --git a/challenge-095/abigail/README.md b/challenge-095/abigail/README.md index dead45f3e0..41d284a063 100644 --- a/challenge-095/abigail/README.md +++ b/challenge-095/abigail/README.md @@ -47,5 +47,6 @@ print $stack->min; # prints -1 ~~~~ ### Solutions +* [C](c/ch-2.c) * [Node](node/ch-2.js) * [Perl](perl/ch-2.pl) diff --git a/challenge-095/abigail/c/ch-2.c b/challenge-095/abigail/c/ch-2.c new file mode 100644 index 0000000000..8dbc929edc --- /dev/null +++ b/challenge-095/abigail/c/ch-2.c @@ -0,0 +1,85 @@ +# include +# include +# include + +int main (void) { + char * line = NULL; + size_t len = 0; + char * error = "Stack is empty"; + + struct node { + long value; + struct node * next; + }; + + struct node * stack; + + while (getline (&line, &len, stdin) != -1) { + /* + * Parse a value from the line of input, and + * push it on the stack. + */ + if (strncmp (line, "push", 4) == 0) { + long val; + if (sscanf (line + 4, " %ld", &val)) { + struct node * head; + head = (struct node *) malloc (sizeof (struct node)); + if (head == NULL) { + fprintf (stderr, "Out of memory!\n"); + exit (1); + } + head -> value = val; + head -> next = stack; + stack = head; + } + } + + /* + * Pop a value from the stack; if the stack is empty, + * this is a no-op. + */ + if (strncmp (line, "pop", 3) == 0 && stack != NULL) { + struct node * next; + next = stack -> next; + free (stack); + stack = next; + } + + /* + * Print the value from the top of the stack; if the + * stack is empty, print an error message. + */ + if (strncmp (line, "top", 3) == 0) { + if (stack == NULL) { + printf ("%s\n", error); + } + else { + printf ("%ld\n", stack -> value); + } + } + + /* + * Find the minimum value in the stack, and print it. + * If the stack is empty, print an error message. + */ + if (strncmp (line, "min", 3) == 0) { + if (stack == NULL) { + printf ("%s\n", error); + } + else { + long min = stack -> value; + struct node * pointer = stack -> next; + while (pointer != NULL) { + if (pointer -> value < min) { + min = pointer -> value; + } + pointer = pointer -> next; + } + printf ("%ld\n", min); + } + } + } + free (line); + + return (0); +} -- cgit