Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Source file for a linked list in C
- *
- * @authors: Michael Denzel
- * @creation_date: 2016-09-05
- * @contact: m.denzel@cs.bham.ac.uk
- */
- //standard includes
- // TODO: Add the includes you need
- #include <stdlib.h>
- #include <stdio.h>
- //own includes
- #include "linkedlist.h"
- // TODO: Implement those methods!
- int get(list * l, unsigned int index){
- if(index > 0)
- {
- return get(l->next, index-1);
- }
- return l->value;
- }
- int prepend(list * l, int data){
- list* preElement = malloc(sizeof(list));
- init(preElement);
- if(preElement == NULL)
- {
- return -1;
- }
- preElement->value = data;
- preElement->next = l;
- return 0;
- }
- int append(list * l, int data){
- if(l->next != NULL)
- {
- return append(l->next, data);
- }
- list* postElement = malloc(sizeof(list));
- init(postElement);
- if(postElement == NULL)
- {
- return -1;
- }
- postElement->value = data;
- l->next = postElement;
- return 0;
- }
- int remove_element(list * l, unsigned int index){
- if(index > 1)
- {
- if(l->next == NULL)
- {
- return -1;
- }
- return remove_element(l->next, index - 1);
- }else if(index == 1)
- {
- if(l->next == NULL)
- {
- return -1;
- }
- list* tail = l->next->next;
- l->next = tail;
- free(l->next);
- }else
- {
- free(l);
- }
- return 0;
- }
- int insert(list * l, unsigned int index, int data){
- if(index > 1)
- {
- if(l->next == NULL)
- {
- return -1;
- }
- return insert(l->next, index - 1, data);
- }else if(index == 1)
- {
- list* newElement = malloc(sizeof(list));
- init(newElement);
- newElement->value = data;
- if(l->next == NULL)
- {
- l->next = newElement;
- }else
- {
- list* tail = l->next;
- l->next = newElement;
- newElement->next = tail;
- }
- }else
- {
- prepend(l, data);
- }
- return 0;
- }
- void print_list(list * l){
- printf("%d", l->value);
- if(l->next != NULL)
- {
- printf(", ");
- print_list(l->next);
- }
- }
- void init(list * l){
- l->next = malloc(sizeof(list*));
- l->value = 0;
- }
- void destroy(list *l){
- if(l->next != NULL)
- {
- destroy(l->next);
- }
- free(l);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement