使用链接列表添加两个数字

时间:2016-12-07 14:59:27

标签: c linked-list

  

2。添加两个数字

     

您将获得两个代表两个非负数的链表。数字以相反的顺序存储,每个节点包含一个数字。添加两个数字并将其作为链接列表返回。

     

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
  输出:7 -> 0 -> 8

我已经完成了Leetcode中第二个问题的代码。当我提交我的答案时,当输入为两个零时,我遇到了运行时错误。但是当我使用自己的自定义Testcase时,它看起来非常好。

我已经仔细检查过我的代码,仍无法找到错误的位置。你能帮帮我吗?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* p1;
    struct ListNode* p2;
    struct ListNode* head;
    head = (struct ListNode*)malloc(sizeof(struct ListNode*));
    struct ListNode* cur = head;

    p1 = l1; p2 = l2;

    int sum, carry = 0, x, y;

    while(p1 || p2)
    {
        //Assign the values of the listnode to x and y.
        if(p1 != NULL) x = p1 -> val; else x = 0;
        if(p2 != NULL) y = p2 -> val; else y = 0;
        sum = x + y + carry;

        //Declare a new node nxt(next) and insert it after the current node
        struct ListNode* nxt;
        nxt = (struct ListNode*)malloc(sizeof(struct ListNode*));
        nxt -> val = sum % 10;
        carry = sum / 10;

        cur -> next = nxt;
        cur = cur -> next;

        if(p1 != NULL) p1 = p1 -> next;
        if(p2 != NULL) p2 = p2 -> next;
    }

    if(carry > 0)
    {
        struct ListNode* nxt;
        nxt = (struct ListNode*)malloc(sizeof(struct ListNode*));
        nxt -> val = carry;
        cur -> next = nxt;
    }

    head = head -> next;

    return head;
}

错误:

The error

自定义测试用例:

custom testcase

1 个答案:

答案 0 :(得分:0)

  

那么如何编辑代码?

正如John Kugelman上面写的那样:

print (df)
   No     Device
0   1  asus best
1   2     Xiaomi
2   3     xiaomi
3   4       Asus
4   5    Samsung

df['Device'] = df['Device'].str.capitalize()
print (df)
   No     Device
0   1  Asus best
1   2     Xiaomi
2   3     Xiaomi
3   4       Asus
4   5    Samsung