CS3413/Assignment1/linked_list.c

113 lines
2.6 KiB
C
Raw Normal View History

2023-09-15 23:55:52 -03:00
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>
#include "node.h"
#define MAX_LEN 100
int contains(Node *head, char *data) {
Node *current = head;
while (current != NULL) {
if (strcmp(current->data, data) == 0) {
return true;
}
current = current->next_elem;
}
return false;
}
2023-09-15 23:55:52 -03:00
Node *search(Node **head, char *data) {
Node *current = *head;
// Only using this function here because the assignment asks for it. There is no reason to do this otherwise
if (contains(current, data) == false) {
return NULL;
}
2023-09-15 23:55:52 -03:00
while (current != NULL) {
if (strcmp(current->data, data) == 0) {
return current;
}
current = current->next_elem;
}
return NULL;
}
2023-09-18 11:39:01 -03:00
2023-09-15 23:55:52 -03:00
Node *searchForPrevious(Node **head, Node *current) {
Node *previous = *head;
while (previous != NULL) {
if (previous->next_elem == current) {
return previous;
}
previous = previous->next_elem;
}
return NULL;
}
void add(Node **head, char *data) {
if (*head == NULL) {
*head = createNode(data);
} else {
Node *current = *head;
while (current->next_elem != NULL) {
current = current->next_elem;
}
current->next_elem = createNode(data);
}
}
void delete(Node **head, char *data) {
2023-09-15 23:55:52 -03:00
if (*head == NULL) {
return;
2023-09-15 23:55:52 -03:00
}
Node *result = search(head, data);
if (result == NULL) {
return;
2023-09-15 23:55:52 -03:00
} else {
Node *previous = searchForPrevious(head, result);
if (previous == NULL) {
// If the node to be deleted is the head
Node *next = result->next_elem;
destroyNode(result);
*head = next;
} else {
// If the node to be deleted is not the head
previous->next_elem = result->next_elem;
destroyNode(result);
}
return;
2023-09-15 23:55:52 -03:00
}
}
void findAndReplace(Node *head, char *data, char *newData) {
Node *current = search(&head, data);
2023-09-15 23:55:52 -03:00
if (current != NULL) {
replaceData(current, newData);
}
}
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%s\n", current->data);
current = current->next_elem;
}
}
int stop(Node **head) {
2023-09-15 23:55:52 -03:00
Node *current = *head;
while (current != NULL) {
Node *next = current->next_elem;
destroyNode(current);
current = next;
}
return true;
}