C链接列表,丢失元素

时间:2015-10-11 11:20:57

标签: c linked-list

我正在尝试编写添加链接列表元素数字的代码。但是在添加之后我失去了一些元素。我找不到错误。这是我的代码:

void push(struct node** head_ref, int new_data){
    struct node* new_node = (struct node*)malloc(sizeof(struct node*));
    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)    = new_node;
}
void reverse(struct node** head_ref){
    struct node* prev   = NULL;
    struct node* current = *head_ref;
    struct node* next;
    while (current != NULL){
        next  = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    *head_ref = prev;
}
struct node *shiftter(struct node *a, int index){
    struct node *temp = a;
    while(index > 0){
        append(&temp, 0);
        --index;
    }
    return temp;
}
struct node *add(struct node *fist, struct node *second){
    struct node *gudu = second;
    struct node *c = fist;
    struct node *hudu = NULL;
    reverse(&gudu);
    reverse(&c);
    while(c != NULL){
        push(&hudu, c->data + gudu->data);
        c = c->next;
        gudu = gudu->next;
    }
    while(gudu != NULL){
        push(&hudu, gudu->data);
        gudu = gudu->next;
    }
    return hudu;
}
int main(int argc, const char * argv[]) {
    struct node *a = NULL;
    struct node *b = NULL;
    push(&a , 1);
    push(&a , 2);
    push(&a , 3);
    push(&a , 4);
    push(&b , 5);
    push(&b , 1);
    push(&b , 2);
    push(&b , 4);
    printList(a);
    printf("\n");
    printList(b);
    printf("\n");
    b = shiftter(b,1);
    printList(b);
    printf("\n");
    printList(add(a, b));
    printf("\n");
    printList(a);
    printf("\n");
    printList(b);
    return 0;
}

我的输出是:

4 3 2 1 

4 2 1 5 

4 2 1 5 0  

4 6 4 7 1 

4

4 

我的程序以退出代码结束:0

2 个答案:

答案 0 :(得分:2)

即使reverse中的算法正确,函数add中的问题也很简单:您反转列表并并行迭代结果列表。但是你没有保留新的头部,所以除了最后一个节点之外的所有节点都不再被任何东西引用。

完成计算后,您应该保留新的头并将其反转以恢复原始列表。

更好的是:将列表保持在从低到高的数字顺序。

答案 1 :(得分:0)

首先,名为reverse的函数不会在reverse列表附近远程执行任何操作。它将最后一个元素(prev)放在列表​​的头部,但是它尽可能接近...其余的逻辑最多是阴天。不应该修改最后一个元素{{ 1}}成员,指向倒数第二个元素?这是我相信你缺少的元素的来源。

P.S。我们仍然没有必要的完整程序来明确回答这个问题。一旦您使用完整/可编译的测试用例更新问题,请给我打电话。

相关问题