Правильно ли реализован двусвязный список - C (СИ)
Формулировка задачи:
Здравствуйте! Пытаюсь на С двусвязный список сделать, вот код:
В чем ошибка? Вообще, правильно ли я делаю список или есть более удобный способ создания, обновления, удаления и т.д.
struct Node {
int count;
struct Node *next;
};
typedef struct Node Item;Item *head = NULL;
add_head (head, "One"); // 1. Здесь в функцию передаю указатель на хеад
printf("HEAD IN MAIN: %d\n", head->count); // 5. Но сюда не передаетсяItem* create_node (char new_word []) {
Item *new_node = (Item *) malloc(sizeof(Item));
new_node->count = 2;
new_node->next = NULL;
return new_node;
}
void add_head (Item *head, char new_word []) {
Item *temp = create_node(new_word); // 2. Создаю новый узел
temp->next = head;
head = temp; // 3. Присваиваю к хеад указатель на новый узел
printf("HEAD IN FUNC: %d\n", head->count); // 4. Здесь все нормально выводится
}Решение задачи: «Правильно ли реализован двусвязный список»
textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
char* text;
struct Node *prev, *next;
};
struct DoubleLinkedList
{
int nodesCount;
struct Node *topSentinel, *bottomSentinel;
};
void CreateList(struct DoubleLinkedList *list)
{
list->topSentinel = (struct Node*)calloc(2, sizeof(struct Node));
list->bottomSentinel = list->topSentinel + 1;
list->topSentinel->next = list->bottomSentinel;
list->bottomSentinel->prev = list->topSentinel;
list->nodesCount = 0;
}
void AddNodeToTop(struct DoubleLinkedList *list, const char* nodeText)
{
size_t bufferLength = strlen(nodeText) + 1;
struct Node *newNode = (struct Node*)calloc(1, sizeof(struct Node));
newNode->next = list->topSentinel->next;
newNode->prev = list->topSentinel;
newNode->next->prev = newNode;
list->topSentinel->next = newNode;
newNode->text = (char*)calloc(bufferLength, sizeof(char));
strncpy(newNode->text, nodeText, bufferLength);
++list->nodesCount;
}
int main()
{
struct DoubleLinkedList list;
CreateList(&list);
AddNodeToTop(&list, "One");
AddNodeToTop(&list, "Two");
AddNodeToTop(&list, "Three");
for (const struct Node *currentNode = list.topSentinel->next; currentNode != list.bottomSentinel; currentNode = currentNode->next)
printf("Node text: %s\n", currentNode->text);
getchar();
return 0;
}
Объяснение кода листинга программы
- Включаем необходимые заголовочные файлы:
, , - Объявляем структуру узла списка: struct Node { char text; struct Node prev, *next; }
- Объявляем структуру двусвязного списка: struct DoubleLinkedList { int nodesCount; struct Node topSentinel, bottomSentinel; }
- Создаем функцию для создания пустого списка: void CreateList(struct DoubleLinkedList *list)
- Создаем функцию для добавления нового элемента в начало списка: void AddNodeToTop(struct DoubleLinkedList list, const char nodeText)
- В функции main создаем экземпляр двусвязного списка и инициализируем его: struct DoubleLinkedList list; CreateList(&list);
- Добавляем три элемента в список: AddNodeToTop(&list,
One); AddNodeToTop(&list,Two); AddNodeToTop(&list,Three); - Выводим текст всех элементов списка в консоль: for (const struct Node *currentNode = list.topSentinel->next; currentNode != list.bottomSentinel; currentNode = currentNode->next) printf(
Node text: %s\n, currentNode->text); - Ждем нажатия клавиши для завершения программы: getchar();
- Возвращаем 0, чтобы указать, что программа успешно завершилась: return 0;