удалить элемент связанного списка с помощью memcmp - PullRequest
0 голосов
/ 06 мая 2011

В этом коде я хочу удалить любой элемент в списке, это делается delpos, я использую memcmp для этого, я делаю это, так как я должен использовать эту же логику в другой программе, где я получаю значение и я должен сравнить это значение, присутствующее в связанном списке, (здесь я буду сравнивать структуру, отстраняющуюся от целого числа), может любой из вас, пожалуйста, расскажет, какую ошибку я совершил в delpos, пока он отображает некоторые ненужные значения.

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

void insertbeg();
void delpos();
void display();

struct node {
    int info;
    struct node *link;
} *first = NULL;

struct node *create();
int item, key;

main() {
    int choice;
    while (1) {
        printf("\nchoices are:\n");
        printf("\n1.Insertbeg\n2.delpos\n3.display\n4.exit\n");
        printf("Enter U'r choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1: insertbeg();
                break;
            case 2: delpos();
                break;
            case 3: display();
                break;
            case 4: exit(1);
            default: printf("INVALID CHOICE TRY AGAIN\n");

        }
    }
}

struct node *create() {
    struct node *new;
    new = (struct node*) malloc(sizeof (struct node));
    return (new);
}

void insertbeg() {
    struct node *new;
    new = create();
    printf("Enter element to be inserted: ");
    scanf("%d", &item);
    if (first == NULL) {
        new->info = item;
        new->link = NULL;
        first = new;
    } else {
        new->info = item;
        new->link = first;
        first = new;
    }
}

void delpos() {
    int key;
    struct node *temp, *prev = NULL;
    int cmp_value, cmp_value1;
    if (first == NULL) {
        printf("LIST IS EMPTY\n");
        return;
    } else {
        temp = first;
        printf("Enter the KEY element which is to be deleted: ");
        scanf("%d", &key);
        while (temp->link != NULL) {
            cmp_value = memcmp(&temp->info, &key, 4);
            if (cmp_value == 0) {
                if (prev == NULL)
                    first = temp->link;
                else
                    prev->link = temp->link;
            }
            else {
                prev = temp;
                cmp_value1 = memcmp(&temp->info, &key, 4);
                temp = temp->link;
                free(temp);
            }            
        }
    }
}

1 Ответ

1 голос
/ 06 мая 2011

Похоже, что ваше условие удаления неверно:

     cmp_value = memcmp(&temp->info, &key, sizeof(int)); // sizeof(int) is better than 4
     if (cmp_value == 0)            // here, the items are the same, so you should delete it
     {
        if (prev == NULL)
           first = temp->link;
        else
           prev->link = temp->link;
           // I think you missed a free(temp); here
     }else                          // here, the items are different
     {
        prev = temp;
        cmp_value1 = memcmp(&temp->info, &key, 4);    // why are you comparing again items ??
        temp = temp->link;
        free(temp);                       // why are you freeing the item ?
     }
     // you have to change the value of your temp pointer at the end of the while loop, otherwise, you are not going to correctly check all the items.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...