Я изучаю, как строить связанные списки в C. Моя программа компилируется, но по какой-то причине я не могу понять, я получаю ошибку сегментации . Я пытался выяснить проблему на некоторое время, но мне не повезло. Вот дефектный код:Ошибка сегментации - Связанный список
int len()
{
struct list * current = head;
int length = 0;
while (current != NULL)
{
length++;
current = current -> next; //move to next node
}
return length;
}
struct list * search (int key)
{
struct list * current = head;
while (current != NULL && current->data != key)
current = current -> next;
if (current != NULL && current -> data == key)
return current;
return NULL;
}
/* Insert a new data element with key d into the end of the list. */
void insert(int d) // at the end
{
struct list * current = head;
struct list * new;
while (current -> next != NULL)
current = current -> next;
new = (struct list *)malloc(sizeof(struct list));
new -> data = d;
current -> next = new;
new -> next = NULL;
}
void insertAfter(int d, int where) // insert at the middle
{
struct list * marker = head;
struct list * new;
while(marker -> data != where)
marker = marker -> next;
new = (struct list*)malloc(sizeof(struct list));
new -> next = marker -> next;
marker -> next = new;
new -> data = d;
}
/* Remove the node with value d from the list */
/* assume no duplicated keys in the list */
/* If the list is empty, call prtError() to display an error message and return -1. */
void delete(int d)
{
struct list * current1 = head;
struct list * current2;
if (len() == 0)
{ //prtError("empty");
exit(0);
}
if (head -> data == d)
{
head = head -> next;
}
//Check if last node contains element
while (current1->next->next != NULL)
current1 = current1->next;
if(current1->next->data == d)
current1->next == NULL;
current1 = head; //move current1 back to front */
while(current1 -> next -> data != d)
current1 = current1 -> next;
current2 = current1 -> next;
current1 -> next = current2 -> next;
}
Я получаю ошибку в сегментации в методе удаления на линии:
while(current1 -> next -> data != d)
Почему это так?
В какой функции вы получаете ошибку сегментации? – Jashaszun
Если вы запустите его в отладчике, где отладчик говорит, что происходит ошибка сегментации? – Simon
Я не думаю, что 'новый' зарезервирован в C, но вы, вероятно, не должны использовать его как имя переменной. Ваша функция 'delete' выглядит как вероятный кандидат, у вас есть' if (head -> data == d) 'w/o check для' NULL' и 'current1-> next-> next', вероятно, тоже не хорошо, и' insert' имеет 'current -> next' w/oa' NULL' чек. –