在C中的链接列表末尾插入节点

时间:2014-09-21 21:14:13

标签: c linked-list

nodes的中间或开头插入LinkedList时,我没有任何问题。但是,最后是不同的。当我尝试打印值时,它会给我一个地址:enter image description here

现在,我将如何构建LinkedList

employeeData ed[4];

node *head = NULL, *list = NULL;

for (int i = 0; i < 4; i++)
    fscanf(file, "%d %s %d %d %lf", &ed[i].EMP_ID, ed[i].name, &ed[i].dept, &ed[i].rank, &ed[i].salary);

head = (node *)malloc(sizeof(node));

head->employee = ed[0];
head->next = NULL;

list = head;

for (int i = 1; i < 5; i++){

    node *ptr = (node *)malloc(sizeof(node));

    ptr->employee = ed[i];
    ptr->next = NULL;

    head->next = ptr;

    head = head->next;
}

以下是我向其添加节点的方法:

node *newNode = (node *)malloc(sizeof(node)), *temptr = list, *endNode = list;

newNode->employee.EMP_ID = id;
strcpy(newNode->employee.name, name);
newNode->employee.dept = dept;
newNode->employee.rank = rank;
newNode->employee.salary = salary;
newNode->next = NULL;

while (endNode->next != NULL) endNode = endNode->next;

if (id < temptr->employee.EMP_ID){
    newNode->next = list;
    list = newNode;
}
else if (id > endNode->employee.EMP_ID){
    endNode->next = newNode;
}
else{

    while ((temptr->next != NULL) && (temptr->next->employee.EMP_ID < newNode->employee.EMP_ID))
        temptr = temptr->next;

    newNode->next = temptr->next;

    temptr->next = newNode;
}

当我尝试删除该值时,它将删除它。但是,它不显示值。

我做错了什么?

由于

1 个答案:

答案 0 :(得分:0)

正如BLUEPIXY所说,问题出在建设期间。

索引必须在4 for (int i = 1; i < 4; i++)

而且,我改变了打印列表的方式。

while (temp->next != NULL){
    printf("");
    temp = temp->next;
}

while (temp != NULL){
    printf("");
    temp = temp->next;
}