From 8ebf2af9526cbc66dfdb1a305cb5d594c19d45b7 Mon Sep 17 00:00:00 2001 From: mo khan Date: Wed, 5 Aug 2020 21:35:29 -0600 Subject: Implement stack peek --- src/02/05/stack.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'src/02/05/stack.c') diff --git a/src/02/05/stack.c b/src/02/05/stack.c index 18a344a..26ef956 100644 --- a/src/02/05/stack.c +++ b/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; +} -- cgit v1.2.3