节点提取不适用于双链表

时间:2019-03-26 16:07:57

标签: c

我试图从双向链接列表中提取第一个节点,然后显示更改,但是在调用函数extractNode之后,它会检索正确的节点,但是列表的属性会获得一些随机值。谁能告诉我如何解决这个问题?

struct Train { 
    int code;
    char* name;
};

struct node {
    Train info;
    node* next;
    node* prev;

};

struct DoubleLinkedList {
    node* first;
    node* last;

};

Train createTrain(int cod, const char* name) {
    Train t;
    t.code = cod;
    t.name = (char*)malloc(sizeof(char)*(1 + strlen(name)));
    strcpy(t.name, name);
    return t;
}
node* createNode(Train t, node* next, node* prev) {
    node* nou = (node*)malloc(sizeof(node));
    nou->info = t;
    nou->next = next;
    nou->prev = prev;

    return nou;
}
DoubleLinkedList insertAtTheBeginning(DoubleLinkedList list,Train a) {
    node* newNode = createNode(a, list.first, NULL);
    if (list.first) {
        newNode->next = list.first;
        list.first->prev = newNode;
        list.first = newNode;
    }
    else {
        list.first = newNode;
        list.last = newNode;
    }

    return list;

}



void displayTrain(Train t) {
    printf("\n name: %s , code:%d \n", t.name, t.code);


}

void crossDoubleLinkedList(DoubleLinkedList list) {
    node* temp = list.first;
    while (temp) {

        displayTrain(temp->info);
        temp = temp->next;
    }

}

node* extractNode(DoubleLinkedList list, int cod) {
    node* extractedNode = NULL;
    if (list.first == NULL) { return extractedNode; }
    if (list.first->info.code == cod) {
        node* extractedNode = createNode(createTrain(list.first->info.code, list.first->info.name), list.first->next, NULL);
        list.first->next->prev = NULL;
            node* copy = list.first;
        list.first = list.first->next;
        free(copy->info.name);
        free(copy);
        copy = NULL;

        return extractedNode;
    }

}

void main() {
    DoubleLinkedList list;
    list.first = NULL;
    list.last = NULL;
        list = insertAtTheBeginning(list, createTrain(1, "train1"));
    list = insertAtTheBeginning(list, createTrain(2, "train2"));
    crossDoubleLinkedList(list);
    node* d = extractNode(list, 2);
    crossDoubleLinkedList(list);
    system("pause");

};

我希望列表中只有train1,但是它有 :信息{code = -572662307 name = 0xdddddddd}火车

0 个答案:

没有答案