Commit 8ebf2af

mo khan <mo.khan@gmail.com>
2020-08-06 03:35:29
Implement stack peek
1 parent 97628eb
Changed files (3)
src/02/05/stack.c
@@ -8,6 +8,16 @@ Node *node_init(int data) {
   return node;
 }
 
+Node *node_tail(Node *self) {
+  Node *current = self;
+  while (current) {
+    if (current->next == NULL)
+      return current;
+    current = current->next;
+  }
+  return NULL;
+}
+
 Stack *stack_init(int data) {
   Stack *stack = malloc(sizeof(Stack));
   stack->head = node_init(data);
@@ -27,3 +37,10 @@ int stack_size(Stack *self) {
 
   return count;
 }
+
+int stack_peek(Stack *self) {
+  Node *tail = node_tail(self->head);
+  if (tail)
+    return tail->data;
+  return -1;
+}
src/02/05/stack.h
@@ -9,3 +9,4 @@ typedef struct {
 
 Stack *stack_init(int data);
 int stack_size(Stack *self);
+int stack_peek(Stack *self);
src/02/05/stack_test.c
@@ -10,6 +10,7 @@ Ensure(Stack, when_pushing_an_item_on_to_a_stack) {
   Stack *stack = stack_init(10);
 
   assert_that(stack_size(stack), is_equal_to(1));
+  assert_that(stack_peek(stack), is_equal_to(10));
 }
 
 TestSuite *stack_tests() {