反转两个链表,然后相加

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */

/**
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */

struct ListNode* reverse(struct ListNode* head)
{
    if (head == NULL || head->next == NULL)
    {
        return head;
    }
    struct ListNode* new_head = NULL;
    struct ListNode* cur = NULL;
    while (head)
    {
        cur = head;
        head = head->next;
        cur->next = new_head;
        new_head = cur;
        
    }
    return new_head;
}


struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2) {
    // write code here
    int carry = 0;
    struct ListNode* head = NULL;
    struct ListNode* p = NULL;
    head1 = reverse(head1); // 7 3 9
    head2 = reverse(head2); // 3 6
    while (head1 || head2 || carry != 0)
    {
        int s = 0;
        if (head1)
        {
            s += head1->val;
            head1 = head1->next;
        }
        if (head2)
        {
            s += head2->val;
            head2 = head2->next;
        }
        p = (struct ListNode*)malloc(sizeof(struct ListNode));
        s += carry;
        p->val = (s % 10);
        carry = s / 10;
        p->next = head;
        head = p;
    }

    return head;
}