添加两个存储为链接列表的数字-无法使用C求解

时间:2019-06-17 09:08:22

标签: c linked-list

我了解问题所在,但无法在“ C”中解决。

'use strict';
function ReBuildArray(source, pick, plus) {
    var retVal = {};
    for(var pck in pick) { // without check will return pick'sKey:undefined
        if(source[pick[pck]]) retVal[pick[pck]] = source[pick[pck]];
    }
    for(var pls in plus) {
        retVal[pls] = plus[pls];
    }
    return retVal;
}

var data = {
  foo: 'fff',
  bar: 'sss',
  aaa: 'gggg'
}

var ret = ReBuildArray(data, ['foo','sss']);

console.info('filtered keys', ret); // {foo: "fff"}

var ret = ReBuildArray(data, ['foo','sss'], {'foo2':'bar'});
console.info('filtered keys + additional', ret); // {foo: "fff", foo2: "bar"}

ret = ReBuildArray(data, ['foo','sss'], {'foo':'bar'});
console.info('filtered, but then rewritten keys', ret) // {foo: "bar"}

获取运行时错误:在'struct ListNode'类型的空指针(solution.c)中的成员访问。 我单独运行了功能“ newnode”,效果很好。

需要帮助,只是一个初学者。

2 个答案:

答案 0 :(得分:0)

处理将新节点添加到空列表的操作:

struct ListNode* newnode(struct ListNode* node, int data){

    struct ListNode* temp = node;
    struct ListNode *newnode = (struct ListNode*)malloc(sizeof(struct ListNode));

    if(temp == NULL){
       newnode->val = data;
       newnode->next = NULL;
       return newnode;
    }
    while(temp->next != NULL){
        temp = temp->next;
    }
    temp->next = newnode;
    newnode->next = NULL;
    newnode->val = data;

    return newnode;
} 

答案 1 :(得分:-1)

撇开进位管理和创建新节点,这是关于如何添加两个存储为链表的数字的可能答案:

typedef struct l{
    int val;
    struct l *next;
}List;

List * add(List *a, List *b){
    List *sum = NULL;
    if(a != NULL && b != NULL){
        sum = malloc(sizeof(List));
        sum->val = a->val + b->val;
    } 
    return sum;
}

int main(void){
    List *a = malloc(sizeof(List));
    List *b = malloc(sizeof(List));
    List *s = malloc(sizeof(List));
    a->val = 3;
    b->val = 8;
    s = add(a,b);
    printf("%d + %d = %d\n", a->val, b->val, s->val);
    return 0;
}