97 lines
2.3 KiB
C
97 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include <stddef.h>
|
|
#include <stdbool.h>
|
|
#include <string.h>
|
|
#include "node.h"
|
|
|
|
#define MAX_LEN 100
|
|
|
|
Node *search(Node **head, char *data) {
|
|
Node *current = *head;
|
|
while (current != NULL) {
|
|
if (strcmp(current->data, data) == 0) {
|
|
return current;
|
|
}
|
|
current = current->next_elem;
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
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);
|
|
replaceData(*head, data);
|
|
} else {
|
|
Node *current = *head;
|
|
while (current->next_elem != NULL) {
|
|
current = current->next_elem;
|
|
}
|
|
current->next_elem = createNode(data);
|
|
replaceData(current->next_elem, data);
|
|
}
|
|
}
|
|
|
|
bool delete(Node **head, char *data) {
|
|
if (*head == NULL) {
|
|
return false;
|
|
}
|
|
|
|
Node *result = search(head, data);
|
|
if (result == NULL) {
|
|
return false;
|
|
} 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 true;
|
|
}
|
|
|
|
}
|
|
|
|
|
|
bool findAndReplace(Node **head, char *data, char *newData) {
|
|
Node *current = search(head, data);
|
|
if (current != NULL) {
|
|
replaceData(current, newData);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
bool stop(Node **head) {
|
|
Node *current = *head;
|
|
while (current != NULL) {
|
|
Node *next = current->next_elem;
|
|
destroyNode(current);
|
|
current = next;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void printList(Node **head) {
|
|
Node *current = *head;
|
|
while (current != NULL) {
|
|
printf("%s\n", current->data);
|
|
current = current->next_elem;
|
|
}
|
|
} |