Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Created by Mi on 24.11.2019.
- //
- #ifndef LINKEDLIST_LINKEDLIST_H
- #define LINKEDLIST_LINKEDLIST_H
- #include <stdlib.h>
- typedef struct Node node;
- typedef struct LinkedList List;
- typedef node* iterator;
- struct Node
- {
- node* next;
- node* prev;
- int _data;
- };
- struct LinkedList
- {
- node* head;
- node* tail;
- iterator iter;
- int length;
- };
- List* CreateList(int t_data)
- {
- List *list = malloc(sizeof(List));
- list->head = malloc(sizeof(node));
- list->tail = list->iter = list->head;
- list->iter->_data = t_data;
- list->iter->next = list->iter->prev = NULL;
- list->length = 1;
- return list;
- }
- node* CreateNode(int t_data)
- {
- iterator new_node = malloc(sizeof(node));
- new_node->prev = new_node->next = NULL;
- new_node->_data = t_data;
- return new_node;
- }
- iterator begin(List *list)
- {
- return list->head;
- }
- iterator end(List *list)
- {
- return list->tail;
- }
- iterator get_iterator(List *list, int t_index)
- {
- list->iter = list->head;
- for(int i = 0; i < t_index; ++i, list->iter = list->iter->next)
- ;
- return list->iter;
- }
- void push_back(List *list, int t_data)
- {
- if (!list)
- {
- puts("List nullptr");
- return;
- }
- if (!list->head->next)
- {
- list->tail = CreateNode(t_data);
- list->length++;
- list->head->next = list->tail;
- list->tail->prev = list->head;
- return;
- }
- list->iter = end(list);
- list->tail = CreateNode(t_data);
- list->iter->next = end(list);
- list->tail->prev = list->iter;
- list->length++;
- }
- void push_front(List *list, int t_data)
- {
- if (!list)
- {
- puts("List nullptr");
- return;
- }
- node* new_node = CreateNode(t_data);
- new_node->prev = NULL;
- new_node->next = begin(list);
- list->head->prev = new_node;
- list->head = new_node;
- list->length++;
- }
- void insert(List *list, int t_data, int t_index)
- {
- if (!list)
- {
- puts("List nullptr");
- return;
- }
- if (t_index > list->length || t_index < 0)
- {
- puts("Out of range!");
- return;
- }
- if (!t_index)
- {
- push_front(list, t_data);
- return;
- }
- if (t_index == list->length)
- {
- push_back(list, t_data);
- return;
- }
- list->iter = begin(list);
- for (int i = 0; i < t_index - 1; ++i, list->iter = list->iter->next)
- ;
- node* new_node = CreateNode(t_data);
- new_node->next = list->iter->next;
- new_node->prev = list->iter;
- list->iter->next = new_node;
- list->length++;
- }
- #endif //LINKEDLIST_LINKEDLIST_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement