【LeetCode OJ 002】Add Two Numbers

来源:互联网 发布:kmspico有病毒 知乎 编辑:程序博客网 时间:2024/06/05 07:58

题目: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

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)     {int flag = 0;ListNode * p,*r;ListNode * h = (struct ListNode *)malloc(sizeof(ListNode *));h->next = NULL;r = h;int num;if (l1 == NULL) return l1;if (l2 == NULL) return l2;while (l1&&l2){num = l1->val + l2->val + flag;if (num<10){p = (struct ListNode *)malloc(sizeof(ListNode *));p->val = num;r->next = p;r = p;flag = 0;}else      //如果两位数相加大于10,则向前进一位{p = (struct ListNode *)malloc(sizeof(ListNode *));p->val = num-10;r->next = p;r = p;flag = 1;}l1 = l1->next;l2 = l2->next;}while (l1)  {num = l1->val + flag;if (num<10){p = (struct ListNode *)malloc(sizeof(ListNode *));p->val = num;r->next = p;r = p;flag = 0;}else{p = (struct ListNode *)malloc(sizeof(ListNode *));p->val = num - 10;r->next = p;r = p;flag = 1;}l1 = l1->next;}while (l2){num = l2->val + flag;if (num<10){p = (struct ListNode *)malloc(sizeof(ListNode *));p->val = num;r->next = p;r = p;flag = 0;}else{p = (struct ListNode *)malloc(sizeof(ListNode *));p->val = num - 10;r->next = p;r = p;flag = 1;}l2 = l2->next;}if (flag) //最后再判断一次判断是否有进位{p = (struct ListNode *)malloc(sizeof(ListNode *));p->val = 1;r->next = p;r = p;}r->next = NULL;return h->next;}


0 0