aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorErik Liodden <eriklio@stud.ntnu.no>2017-11-15 13:46:00 +0100
committerErik Liodden <eriklio@stud.ntnu.no>2017-11-15 16:01:28 +0100
commit4d428d5536f5905a8c2ea17797f7d7bb020a9393 (patch)
tree5862069cfd2ed0254a7e3e1f32c3a1369591d76d
parentd2d0901263fb97ebcf64d4f4b67e65cd5b31e922 (diff)
downloadalgdat-4d428d5536f5905a8c2ea17797f7d7bb020a9393.tar.gz
imporove stack
add stack_peek and stack_length functions. stack_peek places the top element of q in elem_addr (similar to stack_pop), but does not remove the element from the stack. stack_length return the logical length of the stack.
-rw-r--r--include/list.h2
-rw-r--r--src/misc/list.c16
2 files changed, 14 insertions, 4 deletions
diff --git a/include/list.h b/include/list.h
index dd25559..3fa535c 100644
--- a/include/list.h
+++ b/include/list.h
@@ -24,6 +24,8 @@ void stack_init(struct stack *s, size_t elem_size, void (*freefn)(void *));
void stack_dispose(struct stack *s);
void stack_push(struct stack *s, void *elem_addr);
void stack_pop(struct stack *s, void *elem_addr);
+void stack_peek(struct stack *s, void *elem_addr);
+int stack_length(struct stack *s);
/* linked lists */
struct llist {
diff --git a/src/misc/list.c b/src/misc/list.c
index b9efc0b..d16f939 100644
--- a/src/misc/list.c
+++ b/src/misc/list.c
@@ -6,7 +6,6 @@
*/
#include <stdlib.h>
-#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "list.h"
@@ -53,14 +52,23 @@ void stack_push(struct stack *s, void *elem_addr)
s->log_length++;
}
-void stack_pop(struct stack *s, void *elem_addr)
+void stack_peek(struct stack *s, void *elem_addr)
{
assert(s->log_length > 0);
- s->log_length--;
- void *source = (char *)s->elems + (s->log_length * s->elem_size);
+ void *source = (char *)s->elems + ((s->log_length-1) * s->elem_size);
memcpy(elem_addr, source, s->elem_size);
}
+void stack_pop(struct stack *s, void *elem_addr)
+{
+ stack_peek(s, elem_addr);
+ s->log_length--;
+}
+
+int stack_length(struct stack *s)
+{
+ return s->log_length;
+}