diff options
| author | Abigail <abigail@abigail.be> | 2021-01-12 00:51:09 +0100 |
|---|---|---|
| committer | Abigail <abigail@abigail.be> | 2021-01-12 00:51:09 +0100 |
| commit | ab10a3b68a9d0717178741f722c25eabf4240300 (patch) | |
| tree | 520c08a88633f15dc4f551ab7daa6f67f24f8ba6 | |
| parent | 965f6c1732c36d3d81575d0bf34d840e5ffdb0d1 (diff) | |
| download | perlweeklychallenge-club-ab10a3b68a9d0717178741f722c25eabf4240300.tar.gz perlweeklychallenge-club-ab10a3b68a9d0717178741f722c25eabf4240300.tar.bz2 perlweeklychallenge-club-ab10a3b68a9d0717178741f722c25eabf4240300.zip | |
C solution for week 95/part 2.
| -rw-r--r-- | challenge-095/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-095/abigail/c/ch-2.c | 85 |
2 files changed, 86 insertions, 0 deletions
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 <stdlib.h> +# include <stdio.h> +# include <string.h> + +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); +} |
