Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // List implementation
- typedef struct ListNode {
- void* data;
- struct ListNode* next;
- struct ListNode* prev;
- } ListNode;
- typedef struct List {
- int size;
- ListNode* head;
- ListNode* tail;
- size_t type;
- } List;
- List* list_init() {
- List* list = malloc(sizeof(List));
- assert(list);
- list->size = 0;
- list->head = NULL;
- list->tail = NULL;
- return list;
- }
- void list_cleanup(List* list) {
- ListNode* current = list->head;
- while (current != NULL) {
- ListNode* next = current->next;
- free(current);
- current = next;
- }
- free(list);
- }
- void list_push(List* list, void* data) {
- ListNode* node = malloc(sizeof(ListNode));
- assert(node);
- node->data = data;
- node->next = list->head;
- node->prev = NULL;
- if (list->head != NULL) {
- list->head->prev = node;
- } else {
- list->tail = node;
- }
- list->head = node;
- list->size++;
- }
- void list_remove_nth(List* list, int n) {
- assert(n >= 0 && n < list->size);
- ListNode* cur = list->head;
- for (int i = 0; i < n && cur != NULL; i++)
- cur = cur->next;
- if (cur == list->head) {
- list->head = cur->next;
- if (list->head != NULL)
- list->head->prev = NULL;
- else
- list->tail = NULL;
- } else if (cur == list->tail) {
- list->tail = cur->prev;
- list->tail->next = NULL;
- } else {
- cur->prev->next = cur->next;
- cur->next->prev = cur->prev;
- }
- free(cur);
- list->size--;
- }
- void* list_get_nth(List* list, int n) {
- assert(n >= 0 && n < list->size);
- ListNode* cur = list->head;
- for (int i = 0; i < n; i++) {
- cur = cur->next;
- }
- return cur->data;
- }
- // Main function
- List* li = list_init();
- int x = 4;
- int y = 8;
- list_push(li, &x);
- list_push(li, &x);
- list_push(li, &y);
- list_push(li, &x);
- printf("List size is: %d\n", li->size);
- ListNode* cur = li->head;
- printf("Getting list elements with while loop:\n");
- while (cur != NULL) {
- printf("%d\n", *(int*)cur->data);
- cur = cur->next;
- }
- printf("Getting list elements with for loop (list_get_nth):\n");
- for (int i = 0; i < li->size - 1; i++) {
- printf("%d: %d\n", i, *(int*)list_get_nth(li, i));
- }
- list_remove_nth(li, 0);
- list_remove_nth(li, 3);
- printf("List size after removing elements: %d\n", li->size);
- printf("New List elements (using for loop):\n");
- for (int i = 0; i < li->size - 1; i++) {
- printf("%d\n", *(int*)list_get_nth(li, i));
- }
- list_cleanup(li);
Advertisement
Add Comment
Please, Sign In to add comment