LeetCode--Add Two Numbers
来源:互联网 发布:淘宝万艾可 编辑:程序博客网 时间:2024/06/18 08:55
问题
You are given two non-empty linked lists representing two non-negative integers. 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.You may assume the two numbers do not contain any leading zero, except the number 0 itself.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* create() { struct ListNode *node = (struct ListNode *) malloc(sizeof(struct ListNode)); if (node == NULL) { printf("allocation failed\n"); exit(0); } node->next = NULL; return node;}int add(int va1, int va2, int *val) { int flag = 0; *val = va1 + va2; if (*val >= 10) { flag = 1; *val = *val % 10; } return flag;}struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *head = create(); int flag = 0; int val = 0; flag = add(l1->val, l2->val, &val); head->val = val; struct ListNode *p = head; l1 = l1->next; l2 = l2->next; while(l1 != NULL && l2 != NULL) { flag = add(l1->val + flag, l2->val, &val); struct ListNode *node = create(); node->val = val; p->next = node; p = node; l1 = l1->next; l2 = l2->next; } while(l1 != NULL) { struct ListNode *node = create(); if (flag == 1) { flag = add(flag, l1->val, &val); } else { val = l1->val; } node->val = val; p->next = node; p = node; l1 = l1->next; } while(l2 != NULL) { struct ListNode *node = create(); if (flag == 1) { flag = add(flag, l2->val, &val); } else { val = l2->val; } node->val = val; p->next = node; p = node; l2 = l2->next; } if (flag == 1) { struct ListNode *node = create(); node->val = 1; p->next = node; } return head;}
性能
阅读全文
0 0
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- LeetCode | Add Two Numbers
- 【leetcode】Add Two Numbers
- Android中Bitmap和Drawable的相互转换
- JavaScript中定义类或对象
- Java Web架构知识整理
- js中的内置对象
- leetCode---Gas Station
- LeetCode--Add Two Numbers
- HDU
- bigchaindb集群部署(5节点)
- ActiveMQ之HelloWorld
- java 反射
- iOS判断字符串为空的方法
- 合同数据库设计
- 暑期项目开发实训 Day2
- linux下vi命令修改文件及保存等使用方法整理