Skip to content
Snippets Groups Projects
Commit bc778685 authored by jattisha's avatar jattisha
Browse files

add list.c

parents
No related branches found
No related tags found
No related merge requests found
list.c 0 → 100644
#include <assert.h>
#include <stdlib.h>
#include "list.h"
// Takes a valid, sorted list starting at `head` and adds the element
// `new_element` to the list. The list is sorted based on the value of the
// `index` member in ascending order. Returns a pointer to the head of the list
// after the insertion of the new element.
list_t* insert_sorted(list_t* head, list_t* new_element) {
assert(head != NULL);
assert(new_element != NULL);
list_t *before = head, *after = head->next;
if (before->index > new_element ->index) {
new_element->next = head;
head = new_element;
return head;
}
while (after != NULL && after->index < new_element->index) {
before = after;
after = after->next;
if (after == NULL)
break;
}
before->next = new_element;
new_element->next = after;
return head;
}
// Reverses the order of the list starting at `head` and returns a pointer to
// the resulting list. You do not need to preserve the original list.
list_t* reverse(list_t* head) {
assert(head != NULL);
list_t *before = head, *middle = head->next, *after;
if (middle == NULL) {
return head;
}
after = middle->next;
head->next = NULL;
while (after != NULL) {
middle->next = before;
before = middle;
middle = after;
after = after->next;
}
middle->next = before;
head = middle;
return head;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment