[LeetCode]Add Two Numbers
来源:互联网 发布:域名可以一年一年续费 编辑:程序博客网 时间:2024/06/06 14:06
Q:
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
以前写过大整数求和,不过是用数组实现的,这里要求用链表(无头结点),思路是一样的,我就不再叙述了,贴上链接:点击打开链接
in addition,添上链表的创建便于测试,贴代码:
#include <iostream>using namespace std;struct ListNode{int val;ListNode* next;ListNode(int x) :val(x), next(NULL){}};class Solution {public:ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {ListNode* p1 = l1;ListNode* p2 = l2;ListNode* l3 = NULL;ListNode* node =NULL;ListNode* r = l3;int flag = 0;int sum = 0;while (p1!=NULL&&p2!=NULL){sum = (p1->val + p2->val + flag) % 10;flag = (p1->val + p2->val + flag) / 10;node = new ListNode(sum);if (l3 == NULL){l3 = node;}else{r->next = node;}r = node;p1 = p1->next;p2 = p2->next;}while (p1 != NULL){sum = (p1->val + flag) % 10;flag = (p1->val + flag) / 10;node = new ListNode(sum);r->next = node;r = node;p1 = p1->next;}while (p2 != NULL){sum = (p2->val + flag) % 10;flag = (p2->val + flag) / 10;node = new ListNode(sum);r->next = node;r = node;p2 = p2->next;}if (flag == 1){node = new ListNode(1);r->next = node;r = node;}return l3;}ListNode* createList(){ListNode* head = NULL;ListNode* rear = head;;ListNode* p = NULL;int x;while (cin >> x){p = new ListNode(x);if (head == NULL)head = p;elserear->next = p;rear = p;}cin.clear();return head;}};int main() {Solution s;ListNode* l1 = s.createList();ListNode* l2 = s.createList();ListNode* l3 = s.addTwoNumbers(l1, l2);ListNode* l = l3;while (l != NULL){printf("%d ", l->val);l = l->next;}printf("\n");return 0;}
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
- LeetCode 3Sum Closest
- day05-servlet
- 第一章 python中的变量
- 【难】【数学】斐波那契数列的O(logn)解法
- [Debug]Android 编辑xml中Incorrect line ending错误解决方法
- [LeetCode]Add Two Numbers
- HTTP协议详解
- 个人学习计划
- Java开源建站工具
- POJ 3006 Dirichlet's Theorem on Arithmetic Progressions(素数筛+等差数列)
- linux内核模块安装hello
- Linux core dump 分析及相关调试
- 服务器高级开发工程师
- 在Docker容器中部署Web应用