Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <limits.h>
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct _item {
- int value;
- struct _item* next;
- } Item;
- void print_list(Item* head);
- // Aggiunge alla fine
- Item* append(Item* head, int value);
- // Aggiunge all'inizio
- Item* prepend(Item* head, int value);
- // Aggiunge all'indirizzo
- Item* insert_at(Item* head, int value, size_t index);
- // Adds element without ruining sorting property
- // Only works for previusly sorted arrays
- // Example:
- // -> 15
- // 1 9 10 (15) 29 32
- Item* insert_sorted(Item* head, int value);
- int main() {
- // ...
- // Insert solution here
- // ...
- Item* list = NULL;
- list = insert_at(list, 1, 0);
- print_list(list);
- list = insert_at(list, 2, 1);
- print_list(list);
- list = insert_at(list, 3, 0);
- print_list(list);
- list = insert_at(list, 4, 1);
- print_list(list);
- list = insert_at(list, 5, 1);
- print_list(list);
- list = insert_at(list, 6, 1);
- print_list(list);
- return 0;
- }
- // Aggiunge alla fine
- Item* append(Item* head, int value) { return insert_at(head, value, INT_MAX); }
- // Aggiunge all'inizio
- Item* prepend(Item* head, int value) { return insert_at(head, value, 0); }
- // Aggiunge all'indirizzo
- Item* insert_at(Item* head, int value, size_t index) {
- // Se head è null, quindi se non è definita una lista
- if (head == NULL) {
- Item* t_head = (Item*)malloc(sizeof(Item));
- t_head->value = value;
- t_head->next = NULL;
- // Returning new head to be replaced
- return t_head;
- }
- if (index == 0) {
- Item* t_head = (Item*)malloc(sizeof(Item));
- t_head->value = value;
- t_head->next = head;
- // Returning new head to be replaced
- return t_head;
- }
- size_t position = 0;
- Item* _iterator = head;
- // Finds the position for the item to be inserted
- while (_iterator->next != NULL && ++position < index) {
- _iterator = _iterator->next;
- }
- // _iterator -> next == NULL or position == index
- if (_iterator->next == NULL) {
- _iterator->next = (Item*)malloc(sizeof(Item));
- _iterator->next->value = value;
- _iterator->next->next = NULL;
- return head;
- }
- // _iterator -> next != NULL
- Item* old_next = _iterator->next;
- _iterator->next = (Item*)malloc(sizeof(Item));
- _iterator->next->value = value;
- _iterator->next->next = old_next;
- return head;
- }
- void print_list(Item* head) {
- for (Item* _iterator = head; _iterator != NULL; _iterator = _iterator->next) {
- printf("%d -> ", _iterator->value);
- }
- printf("NULL\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement