Issue adding and deleting nodes from a linked list

一曲冷凌霜 提交于 2019-12-12 04:37:23

问题


I have a program that has to take in input from a text file, create a linked list with this input, then be able to add, delete, modify, and query the linked list.

My query and modify functions work fine. My delete function fails under a particular case, and I'm struggling with the add function. No errors from the compiler to help out. It would be greatly appreciated if anyone could point me in the right direction.

The add function is giving me the biggest problems. After a couple hours of debugging and help from a coworker, the closest I've gotten to adding anything is changing

UPDATED: Thanks everyone for the feedback! I ended up discovering the major issue I was having with the help of a co-worker. Apparently I was passing around a value instead of a reference. ** did the trick for both add and delete functions.

void add(employee **head, int addEMP_ID, char* addName, int addDept, int addRank, double addSalary) {
}

void delete(employee **head, int option) {
}

回答1:


If the head node is the one you want to delete, it will be freed after the function delete is called. However, the head pointer is still pointing to the head node which is already freed. This is the reason that cause the seg fault.

One way to change is :

void delete(employee **head, int option) {

employee* current;
employee *del;
current = *head;

if (current != NULL) {
    if (current->EMP_ID == option) {
        del = *head;
        *head = *head->next;
        free(del);
        return;
    }
    while (current->next != NULL) {
        if (current ->next->EMP_ID == option) {
            del = current -> next;
            current->next = current ->next->next;
            free(del);
            return;
        }
    current = current -> next;
    }
}
return;
}



回答2:


Two things to consider.

Start a pseudo-OOP going, pass around a pointer to struct List rather than struct Node.

typedef struct structList {
    employeeData *head; 
}  EmployeeList;

Use the double-pointer iterator to insert and delete.



来源:https://stackoverflow.com/questions/26024824/issue-adding-and-deleting-nodes-from-a-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!