2016-03-07 3 views
1

Функция удаления связанных ссылок C/C++ не удаляет элемент из списка. Вот некоторые из моих кодов;Почему функция удаления связанных ссылок не работает?

struct listIntElement { 
    struct listIntElement *next; 
    int data; 
}; 

typedef struct listIntElement ListIntElement; 
ListIntElement *head = NULL; 

/* 
Inserts a new element infront of the list. 
*/ 
bool insert(ListIntElement **head, int data) { 

    // Allocate memory for new element. The cast is needed here as we are using a C++ compiler. 
    ListIntElement *newElement = (ListIntElement *) malloc(sizeof(ListIntElement)); 

    // Check if memory allocation was succesfull. 
    if (newElement == NULL) 
     return false; 

    // Set the data for the new element of the list. 
    newElement->data = data; 
    // Keep track of the new head of the list. 
    newElement->next = *head; 
    *head = newElement; 

    return true; 
} 

/* 
Deleting an element in the list. 
*/ 
bool remove(ListIntElement **head, ListIntElement *elementToDelete) { 
    ListIntElement *element = *head; 

    // Check for NULL pointers. 
    if (head == NULL || *head == NULL || elementToDelete == NULL) 
     return false; 

    // Special case for the head. 
    if (elementToDelete == *head) { 
     *head = element->next; 
     free(elementToDelete); 
     return true; 
    } 

    // Traversal of the list to find the element to remove. 
    while (element != NULL) { 
     if (element->next == elementToDelete) { 
      // Relink the list so that it does not include the element to be deleted. 
      element->next = elementToDelete->next; 
      free(elementToDelete); 
      return true; 
     } 
     element = element->next; 
    } 
    // elementToDelete was not found. 
    return false; 
} 

/* 
Finding an element in the list. 
*/ 
ListIntElement find(ListIntElement **head, int data) { 
    // Take care of the head as we don't want to use the head 
    // in the traversal operation. 
    ListIntElement *element = *head; 
    while (element != NULL && element->data != data) { 
     element = element->next; 
    } 
    return *element; 
} 

/* 
Displaying the list. 
*/ 
void displayList(ListIntElement **head) { 
    ListIntElement *element = *head; 

    // Check if list is empty. 
    if (head == NULL | *head == NULL) { 
     printf("List is empty\n"); 
    } 

    while (element != NULL) { 
     printf("%d --> ", element->data); 
     element = element->next; 
    } 
    printf("NULL"); 
    printf("\n"); 
} 

Вот мой тестовый код;

/* 
* Testing a linked list. 
*/ 
ListIntElement found; 

printf("Linked list test\n"); 
insert(&head,0); 
insert(&head, 1); 
insert(&head, 2); 
insert(&head, 3); 
insert(&head, 4); 
insert(&head, 5); 
displayList(&head); 
printf("size is: %d\n", size(&head)); 
found = find(&head, 5); 
printf("This was found: %d\n", found.data); 
remove(&head,&found); 
displayList(&head); 

Я нашел этот раздел как раздел, где что-то не так в функции удаления;

// Special case for the head. 
if (elementToDelete == *head) { 
    *head = element->next; 
    free(elementToDelete); 
    return true; 
} 

Обратите внимание, что я использую MS Visual Studio 2015 для написания кода C и использования компилятора C++.

+2

ли это провал, просто ничего не делать, или сбой? Если это сбой, какая ошибка вы получаете? Кроме того, опубликуйте функцию 'find()', поскольку она может обеспечить более глубокое понимание. – stellarossa

+2

Для дальнейшего использования, C! = C++, и обычно нужно только тегировать язык, который они пишут/компилируют (если не запрашивать сравнение или контраст), особенно при изучении языка. – crashmstr

+0

@stellarossa: Нет, авария. Однако при попытке удалить элемент заголовка списка оператор if всегда пропускается. Он не должен пропускать его. Хорошо, я добавлю функцию поиска. – PAT

ответ

1

Из функции поиска вы возвращали копию, а не сам адрес, поэтому ваши изменения не отражались в вызывающей функции. Починил это.

#include <stdio.h> 
#include <stdlib.h> 
#include <stdbool.h> 

#define true 1 
#define false 0 

struct listIntElement { 
    struct listIntElement *next; 
    int data; 
}; 

typedef struct listIntElement ListIntElement; 
ListIntElement *head = NULL; 

/* 
Inserts a new element infront of the list. 
*/ 
bool insert(ListIntElement **head, int data) { 

    // Allocate memory for new element. The cast is needed here as we are using a C++ compiler. 
    ListIntElement *newElement = (ListIntElement *) malloc(sizeof(ListIntElement)); 

    // Check if memory allocation was succesfull. 
    if (newElement == NULL) 
     return false; 

    // Set the data for the new element of the list. 
    newElement->data = data; 
    // Keep track of the new head of the list. 
    newElement->next = *head; 
    *head = newElement; 

    return true; 
} 

/* 
Deleting an element in the list. 
*/ 
bool removeElement (ListIntElement **head, ListIntElement *elementToDelete) { 
    ListIntElement *element = *head; 

    // Check for NULL pointers. 
    if (head == NULL || *head == NULL || elementToDelete == NULL) 
     return false; 

    // Special case for the head. 
    if (elementToDelete == *head) { 
     *head = element->next; 
     free(elementToDelete); 
     return true; 
    } 

    // Traversal of the list to find the element to remove. 
    while (element != NULL) { 
     if (element->next == elementToDelete) { 
      // Relink the list so that it does not include the element to be deleted. 
      element->next = elementToDelete->next; 
      free(elementToDelete); 
      return true; 
     } 
     element = element->next; 
    } 
    // elementToDelete was not found. 
    return false; 
} 


/* 
Finding an element in the list. 
*/ 
ListIntElement *find(ListIntElement **head, int data) { 
    // Take care of the head as we don't want to use the head 
    // in the traversal operation. 
    ListIntElement *element = *head; 
    while (element != NULL && element->data != data) { 
     element = element->next; 
    } 
    return element; 
} 

/* 
Displaying the list. 
*/ 
void displayList(ListIntElement **head) { 
    ListIntElement *element = *head; 

    // Check if list is empty. 
    if (head == NULL | *head == NULL) { 
     printf("List is empty\n"); 
    } 

    while (element != NULL) { 
     printf("%d --> ", element->data); 
     element = element->next; 
    } 
    printf("NULL"); 
    printf("\n"); 
} 

int main() { 
    ListIntElement *found; 

    printf("Linked list test\n"); 
    insert(&head,0); 
    insert(&head, 1); 
    insert(&head, 2); 
    insert(&head, 3); 
    insert(&head, 4); 
    insert(&head, 5); 
    displayList(&head); 
    printf("size is: %d\n", sizeof(&head)); 
    found = find(&head, 5); 
    printf("This was found: %d\n", found->data); 
    removeElement(&head,found); 
    displayList(&head); 

} 

Выход:

Linked list test 
5 --> 4 --> 3 --> 2 --> 1 --> 0 --> NULL 
size is: 4 
This was found: 5 
4 --> 3 --> 2 --> 1 --> 0 --> NULL 
+0

Спасибо UnderDog. Вы абсолютно правы. Я внес изменения, и функция удаления работает так, как ожидалось. :) – PAT

Смежные вопросы