Двусвязный список с итератором - ошибка доступа - C (СИ)
Формулировка задачи:
\\Модератору огромная просьба перенести тему в раздел по си, на автоматизме создал тему тут
Нужно реализовать двусвязный список с итератором на чистом си. Немного изврат, но что поделать.
Не могу понять, почему вываливается ошибка доступа. Вроде все чисто написано.
Вот листинги:
List.h
List.cpp
main.cpp
Помогите разобраться.
struct Item ///Объект
{
int value;
};
struct iterator
{
Item * This;
iterator * next;
iterator * prev;
};
struct ItemList ///Сам список
{
iterator * first;
iterator * last;
long count;
};
///Заголовки
ItemList * list_new();
bool push_back(ItemList * l, int a);
bool push_front(ItemList * l, int a);
bool pop(ItemList * l);
void list_delete(ItemList * l);
int get_count(ItemList * l);
iterator* End(ItemList* l);
iterator* Begin(ItemList* l);
iterator* next(iterator* it);
iterator* prev(iterator* it);
int it_value(iterator* it);
bool it_comp(iterator* it1, iterator* it2);#include "List.h"
#include <iostream>
ItemList * list_new() ///Конструктор нового списка
{
ItemList * newList = (ItemList*)malloc(sizeof(ItemList)*1);
newList->first = newList->last = NULL;
newList->count = 0;
return newList;
}
iterator* End(ItemList* l)
{
return l->last;
}
iterator* Begin(ItemList* l)
{
return l->first;
}
iterator* next(iterator* it)
{
return (it->next);
}
iterator* prev(iterator* it)
{
return (it->prev);
}
int it_value(iterator* it)
{
return (it->This->value);
}
bool it_comp(iterator* it1, iterator* it2)
{
return (it1->This->value > it2->This->value);
}
bool push_back(ItemList * l, int a) ///Добавить новый элемент a в конец списка
{
Item* n = (Item*) malloc (sizeof(Item)*1);
iterator* it = (iterator*)malloc(sizeof(iterator)*1);
if (n == NULL || l == NULL)
return false;
n -> value = a;
it -> This = n;
it -> prev = l-> last;
it -> next = NULL;
l -> last = it;
l -> count += 1;
return true;
}
int get_count(ItemList * l)
{
return l->count;
}
bool push_front(ItemList * l, int a) ///Добавить новый элемент a в начало
{
Item* n = (Item*) malloc (sizeof(Item)*1);
iterator* it = (iterator*)malloc(sizeof(iterator)*1);
if (n == NULL || l == NULL)
return false;
n -> value = a;
it -> This = n;
it -> next = l->first;
it -> prev = NULL;
l -> first = it;
l -> count += 1;
return true;
}#include "List.h"
#include <iostream>
int main()
{
ItemList* a = list_new();
for (int i = 0; i < 10; i++)
{
push_front(a, 1000*i);
}
printf("%d ", get_count(a));
iterator* it;
for (it = Begin(a); it != NULL; it = next(it));
{
printf("%d ", it_value(it));
}
return 0;
}Решение задачи: «Двусвязный список с итератором - ошибка доступа»
textual
Листинг программы
#include <stdio.h>
#include <malloc.h>
typedef struct _node {
int data;
struct _node *prev;
struct _node *next;
} node;
typedef struct {
node *first;
node *last;
int count;
} list;
void push_back (list *l, int d) {
node *n= (node*)malloc (sizeof (node));
n->data= d;
n->prev= l->last;
n->next= 0;
if (l->last) l->last->next= n;
l->last= n;
if (!l->count++) l->first= n;
}
void push_front (list *l, int d) {
node *n= (node*)malloc (sizeof (node));
n->data= d;
n->prev= 0;
n->next= l->first;;
if (l->first) l->first->prev= n;
l->first= n;
if (!l->count++) l->last= n;
}
int main() {
list l= {0};
int i;
node *n;
for (i=0; i < 5; i++) push_back (&l, i);
for (i=5; i < 10; i++) push_front (&l, i);
printf ("Count: %d\n", l.count);
for (n= l.first; n; n= n->next) printf ("%d\t", n->data);
printf ("\n");
for (n= l.last; n; n= n->prev) printf ("%d\t", n->data);
printf ("\n");
return 0;
}
Объяснение кода листинга программы
- Включаются необходимые заголовочные файлы
- Объявляются структуры данных: узел и список
- Определяются функции для работы со списком: push_back, push_front
- Создается список и инициализируется начальными значениями
- В цикле добавляются элементы в список с помощью функции push_back
- Затем добавляются элементы в список с помощью функции push_front
- Выводится количество элементов в списке
- В цикле выводятся элементы списка в порядке их добавления с помощью функции push_back
- Затем выводятся элементы списка в обратном порядке с помощью функции push_front
- Программа завершается успешно