Commit 6db0bd1
Changed files (1)
src
01
06
src/01/06/min_stack.c
@@ -2,6 +2,14 @@
#include <stdio.h>
#include <stdlib.h>
+/**
+ * The equivalent of a constructor for initialzing
+ * a new Node in a linked list.
+ *
+ * @param data The data to bind to the node
+ * @param next The next node to point to. NULL for a new head.
+ * @return The new linked list Node.
+ */
static Node *new (int data, Node *next) {
Node *node = malloc(sizeof(Node));
node->next = next;
@@ -9,6 +17,12 @@ static Node *new (int data, Node *next) {
return node;
}
+/**
+ * The equivalent of a constructor for initialzing
+ * a new min Stack.
+ *
+ * @return The new Stack
+ */
Stack *initialize(void) {
Stack *self = malloc(sizeof(Stack));
self->head = NULL;
@@ -17,8 +31,19 @@ Stack *initialize(void) {
return self;
}
+/**
+ * Returns the number of items on the stack.
+ *
+ * @param self The stack to investigate.
+ */
int size(Stack *self) { return self->size; }
+/**
+ * Pushes a new item on to a Stack
+ *
+ * @param self The stack to push the data on to
+ * @param data The data to push on to the Stack
+ */
void push(Stack *self, int data) {
if (!self->min || (data < self->min->data))
self->min = new (data, self->min);
@@ -27,6 +52,12 @@ void push(Stack *self, int data) {
self->size++;
}
+/**
+ * Iterates through each item in a linked list.
+ *
+ * @param head The head of the linked list
+ * @block The callback function to invoke on each item in the list.
+ */
void each(Node *head, Visitor block) {
Node *tmp = head;
@@ -36,6 +67,11 @@ void each(Node *head, Visitor block) {
}
}
+/**
+ * Returns the minimum value in the Stack.
+ *
+ * @param self The stack to investigate
+ */
int min(Stack *self) {
if (self->min)
return self->min->data;
@@ -55,6 +91,11 @@ int min(Stack *self) {
return (int)NULL;
}
+/**
+ * Pops off the item from the top of the Stack.
+ *
+ * @param self The stack to pop an item off of.
+ */
int pop(Stack *self) {
if (!self->head)
return (int)NULL;
@@ -70,8 +111,18 @@ int pop(Stack *self) {
return data;
}
+/**
+ * Prints a visual representation a Node in the linked list.
+ *
+ * @param node The node to print.
+ */
void print_node(Node *node) { printf("[%d]", node->data); }
+/**
+ * A helper function to print out a visual representation of a Stack.
+ *
+ * @param stack the Stack to print out.
+ */
void inspect(Stack *stack) {
printf("\t");
each(stack->head, &print_node);