leetcode 2. Add Two Numbers

//Definition for singly-linked list.
#include <stdio.h>
#include <malloc.h>
#include <ctype.h>
struct ListNode {
    int val;
    struct ListNode *next;
};

void addNode(struct ListNode **head, struct ListNode **p, int val)
{
    if (*head == NULL)
    {
        *head = (struct ListNode*)malloc(sizeof(struct ListNode));
        (*head)->val = val;
        (*head)->next = NULL;
        *p = *head;
    }
    else
    {
        struct ListNode *tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
        tmp->val = val;
        tmp->next = NULL;
        (*p)->next = tmp;
        (*p) = (*p)->next;
    }
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *p1 = l1, *p2 = l2, *p = NULL, *head = NULL;
    int a = 0, b = 0, c = 0;
    for (; p1 != NULL && p2 != NULL; p1 = p1->next, p2 = p2->next)
    {
        c = p1->val + p2->val + a;
        b = c % 10;
        a = c / 10;
        addNode(&head, &p, b);
    }
    p1 = (p1 == NULL ? p2 : p1);
    for (; p1 != NULL; p1 = p1->next)
    {
        c = p1->val + a;
        b = c % 10;
        a = c / 10;
        addNode(&head, &p, b);
    }
    for (; a > 0; a /= 10)
    {
        addNode(&head, &p, a);
    }
    return head;
}

struct ListNode *Input(const char *str)
{
    struct ListNode *p = NULL, *head = NULL;
    const char *c = str;
    for (; *c != '\0'; c++)
    {
        if (isdigit(*c))
        {
            if (p == NULL)
            {
                head = (struct ListNode*)malloc(sizeof(struct ListNode));
                head->val = *c - '0';
                head->next = NULL;
                p = head;
            }
            else
            {
                struct ListNode *tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
                tmp->next = NULL;
                tmp->val = *c - '0';
                p->next = tmp;
                p = p->next;
            }
        }
    }
    return head;
}

void dump(struct ListNode *head)
{
    printf("[");
    for (; head != NULL; head = head->next)
    {
        printf("%d", head->val);
        if (head->next != NULL)
        {
            printf(",");
        }
    }
    printf("]\n");
}

int main()
{
    struct ListNode *l1 = NULL, *l2 = NULL, *head = NULL;
    static char tmp[100];
    scanf("%s", tmp);
    l1 = Input(tmp);
    scanf("%s", tmp);
    l2 = Input(tmp);
    dump(l1);
    dump(l2);
    head = addTwoNumbers(l1, l2);
    dump(head);
    scanf("%s", tmp);
    return 0;
}

 

posted @ 2016-08-28 13:43  你好阿汤哥  Views(176)  Comments(0Edit  收藏  举报