Add Two Numbers(LeetCode)
来源:互联网 发布:福建晨曦软件下载 编辑:程序博客网 时间:2024/05/16 10:43
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
这是一个基础的链表问题,需要注意的是初始链表l1,l2可能为NULL的情况,则可直接返回另一链表。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { int flag = 0; if( l1 == NULL ) return l2; else if( l2 == NULL ) return l1; ListNode *p,*head = new ListNode(0); p = head; head -> val = (l1 -> val + l2 -> val) % 10; flag = (l1 -> val + l2 -> val) / 10; l1 = l1 -> next; l2 = l2 -> next; while( l1 != NULL || l2 != NULL) { int num1 = 0,num2 = 0; int num; if( l1 != NULL ) { num1 = l1 -> val; l1 = l1 -> next; } if( l2 != NULL ) { num2 = l2 -> val; l2 = l2 -> next; } num = ( num1 + num2 + flag ) % 10; flag = ( num1 + num2 + flag ) / 10; ListNode *q = new ListNode(num); p -> next = q; p = p -> next; } if( flag != 0 ) { ListNode *q = new ListNode(1); p -> next = q; p = p -> next; } 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
- UVa 409 - Excuses, Excuses!
- 求最大公约数,及最小公倍数。
- C语言标准函数库
- UVa 457 - Linear Cellular Automata
- c++文件操作乱码问题
- Add Two Numbers(LeetCode)
- C语言控制台窗口图形界面编程(四):文本输出
- Cisco 2940交换机电源故障维修
- 怎么做网站推广-网站推广100种方法
- UIRefreshControl iOS6 和 iOS7的风格
- 将对象转换为json字符串
- fedora14 编译arm Linux make menuconfig error处理方法
- SQLServer中数据加密方法
- 阻塞状态的recv返回值