Leetcode2
来源:互联网 发布:mac文明5汉化包下载 编辑:程序博客网 时间:2024/05/22 02:31
2.
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
注意:两个链表中的数字为逆序排列,输入为2 -> 4 -> 3和5 -> 6 -> 4,实际上相加时为342+465=807,输出时也要逆序:708。
参考戴方勤的源代码:
/**
* 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) {
ListNode dummy(-1);
int carry=0;
ListNode *prev=&dummy;
for(ListNode *pa=l1,*pb=l2;pa!=nullptr||pb!=nullptr;
pa=pa==nullptr?nullptr:pa->next,pb=pb==nullptr?nullptr:pb->next,prev=prev->next){
int ai=pa==nullptr?0:pa->val;
int bi=pb==nullptr?0:pb->val;
int value=(ai+bi+carry)%10;
carry=(ai+bi+carry)/10;
prev->next=new ListNode(value);
}
if(carry>0)
prev->next=new ListNode(carry);
return dummy.next;
}
};
结构体中已经定义:
ListNode(int x) : val(x), next(NULL) {}
即创建一个只有整型数作为输入的节点,则默认该节点的next指针为空。
创建的结点:
ListNode dummy(-1);
为头结点,数据域为-1,指针域为空。
carry为进位标志。
ListNode *prev=&dummy; 定义一个指针,指向dummy头结点,为活动指针。
if(carry>0)
prev->next=new ListNode(carry);如果最后一位相加后有进位,则开辟一个新结点存放进位。
return dummy.next;返回结果链表的头结点指针。以便访问链表中的每个结点。
0 0
- leetcode2
- Leetcode2
- leetcode2
- leetcode2
- LeetCode2 AddTowNumbers
- leetcode2 multi_string
- LeetCode2-AddTwoNumbers
- leetcode2:inorder tranversal
- [LeetCode2]Add Two Numbers
- leetcode2 add two numbers
- LeetCode2 Add Two Numbers
- Leetcode2: Rotate Array
- leetcode2 two sum
- leetcode2.1.8.3sum
- LeetCode2.1.10(4Sum)
- LeetCode2.1.11(Remove Element)
- LeetCode2.1.12(Next Permutation)
- LeetCode2.1.16(Rotate Image)
- cas取消HTTPS协议
- Grunt压缩、合并js/css文件
- MVC设计模式
- quartz的job中注入spring对象!
- 多线程
- Leetcode2
- Xcode clang 编译器
- 给JFinal添加Shiro插件功能,支持Shiro所有注解
- 打包java项目并生成可执行文件exe
- Android按钮单击事件的四种常用写法总结
- Linux环境jdk安装
- Xcode中修改变量名、类名及字符串的替换操作
- MySQL引擎---读写分离对不同引擎的选择
- java设计模式之建造者模式