Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge branch 'shift'

  • Loading branch information...
commit be46abc6df782e06da43d3e33772eb98068ef43b 2 parents 2f15a25 + 66048fa
@tj tj authored
Showing with 49 additions and 0 deletions.
  1. +17 −0 src/list.c
  2. +1 −0  src/list.h
  3. +31 −0 test.c
View
17 src/list.c
@@ -81,6 +81,23 @@ List_pop(List *self) {
}
/*
+ * Return / detach the first node in the list, or NULL.
+ */
+
+ListNode *
+List_shift(List *self) {
+ if (!self->len) return NULL;
+ ListNode *node = self->head;
+ if (--self->len) {
+ (self->head = node->next)->prev = NULL;
+ } else {
+ self->head = self->tail = NULL;
+ }
+ node->next = node->prev = NULL;
+ return node;
+}
+
+/*
* Prepend the given node to the list
* and return the node, NULL on failure.
*/
View
1  src/list.h
@@ -76,6 +76,7 @@ ListNode *List_unshift(List *self, ListNode *node);
ListNode *List_find(List *self, void *val);
ListNode *List_at(List *self, int index);
ListNode *List_pop(List *self);
+ListNode *List_shift(List *self);
void List_remove(List *self, ListNode *node);
void List_destroy(List *self);
View
31 test.c
@@ -234,6 +234,36 @@ test_List_pop() {
}
static void
+test_List_shift() {
+ // Setup
+ List *list = List_new();
+ ListNode *a = List_push(list, ListNode_new("a"));
+ ListNode *b = List_push(list, ListNode_new("b"));
+ ListNode *c = List_push(list, ListNode_new("c"));
+
+ // Assertions
+ assert(3 == list->len);
+
+ assert(a == List_shift(list));
+ assert(2 == list->len);
+ assert(b == list->head);
+ assert(NULL == list->head->prev && "new head node prev is not NULL");
+ assert(NULL == a->prev && "detached node prev is not NULL");
+ assert(NULL == a->next && "detached node next is not NULL");
+
+ assert(b == List_shift(list));
+ assert(1 == list->len);
+
+ assert(c == List_shift(list));
+ assert(0 == list->len);
+ assert(NULL == list->head);
+ assert(NULL == list->tail);
+
+ assert(NULL == List_shift(list));
+ assert(0 == list->len);
+}
+
+static void
test_ListIterator() {
// Setup
List *list = List_new();
@@ -286,6 +316,7 @@ main(int argc, const char **argv){
test(List_at);
test(List_remove);
test(List_pop);
+ test(List_shift);
test(List_destroy);
test(ListIterator);
puts("... \x1b[32m100%\x1b[0m\n");
Please sign in to comment.
Something went wrong with that request. Please try again.