2026-rff_mp/stepushovgs/data-structures/sorce/linked_list.c
GordStep d9d935c0bf implementing a linked list
- insert
- delete
- find
- listAll
2026-04-19 00:31:51 +03:00

142 lines
2.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linked_list.h"
int getListNodeLength(Node* HEAD)
{
int len = 0;
Node* current = HEAD;
while (current != NULL)
{
len++;
current = current->next;
}
return len;
}
// Добавление в конец
Node* insert(Node* head, char name[NAME_BUFF_SIZE], char phone[PHONE_BUFF_SIZE], int show)
{
Node* newNode = (Node*)malloc(sizeof(Node));
strcpy_s(newNode->name_, NAME_BUFF_SIZE, name);
strcpy_s(newNode->phone_, PHONE_BUFF_SIZE, phone);
newNode->next = NULL;
printf("Data: %s %s\n", name, phone);
printf("New Data: %s %s\n", newNode->name_, newNode->phone_);
if (head == NULL)
{
printf("\nNew list\n");
head = newNode;
return newNode;
}
Node* last = head;
int ind = 0;
while (last->next != NULL)
{
if (show == 1)
printf("%d \n", ind++);
last = last->next;
}
last->next = newNode;
return head;
}
char* find(Node* HEAD, char target_name[NAME_BUFF_SIZE])
{
Node* current = HEAD;
while (current != NULL)
{
if (strcmp(target_name, current->name_) == 0)
{
return current->phone_;
}
current = current->next;
}
return NULL;
}
// Вывод всех элементов
void printAllNodes(Node* head)
{
Node* current = head;
int ind = 0;
while (current != NULL)
{
printf("Ind: %d\nName: %s\nPhone: %s\n", ind++, current->name_, current->phone_);
current = current->next;
}
}
Node* deleteNode(Node* HEAD, char target_name[NAME_BUFF_SIZE])
{
Node* privious = HEAD;
Node* current = HEAD->next;
while (current != NULL)
{
if (strcmp(target_name, current->name_) == 0)
{
privious->next = current->next;
break;
}
privious = current;
current = current->next;
}
return HEAD;
}
Node* listAll(Node* HEAD)
{
if (HEAD == NULL)
{
return NULL;
}
int len = getListNodeLength(HEAD);
Node* current = HEAD;
Node* list = (Node*)malloc(len * sizeof(Node));
int ind = 0;
while (current != NULL)
{
list[ind++] = *current;
current = current->next;
}
return list;
}
void printNode(Node node)
{
printf("%s ", node.name_);
printf("%s\n", node.phone_);
}
void printListNode(Node* list, int length)
{
printf("\n\n%d\n", length);
for (int i = 0; i < length; i++)
{
printNode(list[i]);
}
}