leetcode(2) - Add Two Numbers

来源:互联网 发布:淘宝上的自行车怎么样 编辑:程序博客网 时间:2024/04/20 19:34

题目要求:

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8



/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {    if (!l1 && !l2) return NULL;    if (!l1) return l2;    if (!l2) return l1;        struct ListNode *p1 = l1;    struct ListNode *p2 = l2;    int add_num = 0;   //需要注意进位 (1)最后一位的进位需要新建结点存储进位   (2)如果两个链表的长度不一样的进位    int add_num_tmp = 0;    struct ListNode *head = NULL;    //需要注意尾插法第一次需要判断头结点为空的情况单独处理    struct ListNode *head_p = NULL;        while(p1 && p2) {                    struct ListNode *new_Node = (struct ListNode *)malloc(sizeof(struct ListNode));              new_Node->next = NULL;        add_num_tmp = add_num;        add_num = (p1->val + p2->val + add_num_tmp) / 10;        new_Node->val = (p1->val + p2->val + add_num_tmp) % 10;                        if (head == NULL) {            head = new_Node;            head_p = head;        }        else {            head_p->next = new_Node;            head_p = head_p->next;        }                p2=p2->next;        p1=p1->next;          }    while (p1) {            add_num_tmp = add_num;            add_num = (p1->val + add_num_tmp) / 10;            p1->val = (p1->val + add_num_tmp) % 10;              head_p->next=p1;        head_p = head_p->next;        p1=p1->next;    }    while (p2) {            add_num_tmp = add_num;            add_num = (p2->val + add_num_tmp) / 10;            p2->val = (p2->val + add_num_tmp) % 10;             head_p->next=p2;        head_p = head_p->next;        p2=p2->next;    }   /* when add_num > 0 , we should create a new node to store */    if (add_num>0) {         struct ListNode *new_Node = (struct ListNode *)malloc(sizeof(struct ListNode));         new_Node->val = add_num;         new_Node->next = NULL;         head_p->next = new_Node;         head_p = head_p->next;    }        return head;            }


0 0
原创粉丝点击