revert a list

master
orange 11 years ago
parent 469f5a7da3
commit 7e828ad441

@ -81,9 +81,36 @@ void list_remove(list_t * list, list_node_t * item) {
}
}
/* FIXME
* list_node_t list_revert(list_node_t *list) {
} */
void list_revert(list_t *list) {
list_t reverted;
reverted.head = NULL;
list_node_t *cur = list->head;
while (cur != NULL) {
list_node_t *next = cur->next;
list_node_t *headbefore = reverted.head;
reverted.head = cur;
cur->next = headbefore;
cur = next;
}
list->head = reverted.head;
}
list_node_t* list_elementat(list_t *list, int i) {
if (i > list_length(list)-1) {
return NULL;
}
list_node_t *cur = list->head;
for (int j=0; j < i; j++) {
cur = cur->next;
}
return cur;
}
int main(int argc, char *argv[]) {
list_t *emptylist = malloc(sizeof(list_t));
@ -167,4 +194,35 @@ int main(int argc, char *argv[]) {
assert(list_empty(foolist) == true);
list_print(foolist);
printf("list_length = %d\n", list_length(foolist));
/* revert a list */
const int howmany2 = 10;
for (int i = 0; i < howmany2; i++) {
list_node_t *newnode = malloc(sizeof(list_node_t));
newnode->data = i;
list_add(foolist, newnode);
}
for (int i = 0; i < howmany2; i++) {
list_node_t *el = list_elementat(foolist, i);
assert(el->data == i);
}
assert(list_length(foolist) == howmany2);
list_print(foolist);
printf("list_length = %d\n", list_length(foolist));
list_revert(foolist);
for (int i = 0; i < howmany2; i++) {
list_node_t *el = list_elementat(foolist, i);
assert(el->data == howmany2-i-1);
}
assert(list_length(foolist) == howmany2);
list_print(foolist);
printf("list_length = %d\n", list_length(foolist));
/* FIXME: frees */
}

Loading…
Cancel
Save