Skip to content

Instantly share code, notes, and snippets.

@andiogenes
Last active March 16, 2018 04:00
Show Gist options
  • Save andiogenes/e13daf0f0e887d599b2da44986b2cad8 to your computer and use it in GitHub Desktop.
Save andiogenes/e13daf0f0e887d599b2da44986b2cad8 to your computer and use it in GitHub Desktop.
Yet another doubly linked list
#include <stdio.h>
#include <stdlib.h>
// другие компиляторы могут потребовать особого хедера для работы с памятью
typedef struct {
int cnt;
char name[255];
} Data;
// SList фактически узел списка, доступ к списку осуществляется через указатель на узел
struct SList {
Data data;
struct SList *prev;
struct SList *next;
};
// Создание первого узла списка с данными
struct SList * create_list(const Data content)
{
struct SList * n_list = (struct SList*)malloc(sizeof(struct SList));
if (n_list == NULL) return NULL;
n_list->data = content;
n_list->prev = n_list->next = NULL;
return n_list;
}
// Добавление предыдущего узла к текущему (с учетом существования предыдущего узла)
struct SList * add_prev(struct SList * c_list, const Data content)
{
struct SList * n_list = create_list(content);
if (n_list == NULL) return NULL;
n_list->next = c_list;
if (c_list->prev != NULL)
c_list->prev->next = n_list;
c_list->prev = n_list;
return n_list;
}
// Добавление следующего узла к текущему
struct SList * add_next(struct SList * c_list, const Data content)
{
struct SList * n_list = create_list(content);
if (n_list == NULL) return NULL;
n_list->prev = c_list;
if (c_list->next != NULL)
c_list->next->prev = n_list;
c_list->next = n_list;
return n_list;
}
// Удаление единственного узла с изменением связей соседних узлов
void remove_one(struct SList * r_list)
{
if (r_list->prev != NULL)
r_list->prev->next = r_list->next;
if ( r_list->next != NULL)
r_list->next->prev = r_list->prev;
free(r_list);
}
// Удаление узлов начиная с текущего слева и справа, возвращает количество удаленных узлов
int remove_list(struct SList * r_list, int isToward)
{
int cnt = 0;
struct SList * cur_rem_list = r_list;
if (isToward) {
while (cur_rem_list->next != NULL) {
struct SList * temp_list = cur_rem_list;
cur_rem_list = cur_rem_list->next;
free(temp_list);
cnt++;
}
} else {
while (cur_rem_list->prev != NULL) {
struct SList * temp_list = cur_rem_list;
cur_rem_list = cur_rem_list->prev;
free(temp_list);
cnt++;
}
}
free(cur_rem_list);
return ++cnt;
}
int main()
{
Data raph = {1, "Raphael"};
struct SList *test = create_list(raph);
raph.cnt = 5;
add_next(test, raph);
printf("%d %d %s %s\n", test->data.cnt, test->next->data.cnt, test->data.name, test->prev);
printf("%d %s\n", test->next->data.cnt, test->next->data.name);
printf("%d", remove_list(test, 1));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment