Files
C/008LinkedList/linkedList.c
T
2026-05-15 13:26:54 -04:00

131 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void append(struct Node *head, int data);
void printList(struct Node *head);
void insertAfter(struct Node *head, int key, int data);
void deleteLast(struct Node *head);
void deleteNode(struct Node *head, int key);
int main(int argc, char *argv[]) {
struct Node *head = (struct Node *)malloc(sizeof(struct Node));
printList(head);
append(head, 1);
append(head, 1);
append(head, 2);
append(head, 3);
append(head, 5);
append(head, 8);
insertAfter(head, 3, 6);
printList(head);
deleteLast(head);
printList(head);
deleteNode(head, 2);
printList(head);
deleteNode(head, 9);
return 0;
}
void append(struct Node *head, int data) {
struct Node *newNode, *prev, *current = head;
newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
while (current) {
prev = current;
current = current->next;
}
prev->next = newNode;
newNode->next = current;
}
void printList(struct Node *head) {
struct Node *current = head->next;
if (!current) {
printf("error: nothing to print, list is empty\n");
return;
}
printf("head->");
while (current) {
printf("%i->", current->data);
current = current->next;
}
printf("END\n");
}
void insertAfter(struct Node *head, int key, int data) {
struct Node *current = head;
while (current) {
if (current->data == key)
break;
current = current->next;
}
if (!current) {
printf("error: could not insertAfter. current is NULL\n");
return;
}
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = current->next;
current->next = newNode;
}
void deleteLast(struct Node *head) {
if (!head->next) {
printf("error: list is empty nothing to delete\n");
return;
}
struct Node *prev = NULL, *current = head;
while (current->next) {
prev = current;
current = current->next;
}
prev->next = NULL;
free(current);
}
void deleteNode(struct Node *head, int key) {
int found = 0;
struct Node *prev = NULL, *current = head;
while (current->next) {
if (current->data == key) {
found = 1;
break;
}
prev = current;
current = current->next;
}
// check
if (!found) {
printf("error: node %i not in list, nothing to delete\n", key);
return;
}
//
prev->next = current->next;
free(current);
}