LeetCode-Algorithm2 C++的链表
来源:互联网 发布:ubuntu 查看内核版本 编辑:程序博客网 时间:2024/06/03 16:31
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
这道题如果采用链表来做的话要考验一下细心程度,最后要判断一下是否有carryout,而不能仅以l1和l2是否为空来判断是否可以返回答案了。
还有C++中链表的节点支持构造器,比如:
struct ListNode{int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};就可以直接new ListNode(0)来构造一个val=0,next=NULL的新节点了
链表解法:
class Solution{int unit,tempsum;bool carryout=false;public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){ListNode *pans=new ListNode(0);ListNode *ans = pans;if (l1->val + l2->val >= 10){carryout = true;pans->val = (l1->val + l2->val) % 10;}else{pans->val = l1->val + l2->val;carryout = false;}l1 = l1->next;l2 = l2->next;while (l1 != NULL||l2 != NULL){pans->next = new ListNode(0);pans = pans->next;if (l1 != NULL&&l2 != NULL){if (carryout == true){pans->val = 1;}tempsum = pans->val + l1->val + l2->val;if (tempsum >= 10){pans->val = tempsum % 10;carryout = true;}else{pans->val = tempsum;carryout = false;}l1 = l1->next;l2 = l2->next;}else if (l1 == NULL&&l2 != NULL){if (carryout == true){pans->val = 1;}tempsum = pans->val + l2->val;if (tempsum >= 10){pans->val = tempsum % 10;carryout = true;}else{pans->val = tempsum;carryout = false;}l2 = l2->next;}else if (l1 != NULL&&l2 == NULL){if (carryout == true){pans->val = 1;}tempsum = pans->val + l1->val;if (tempsum >= 10){pans->val = tempsum % 10;carryout = true;}else{pans->val = tempsum;carryout = false;}l1 = l1->next;}}if (carryout == true){pans->next = new ListNode(1);}return ans;}};还有突然发现国外的OJ都是给定了接口,只让你实现一个函数,而不是全部代码都由你编写,做了那么多国内的OJ还是有点不习惯。用面向对象的语言写算法也确实没有面向过程那么习惯。
0 0
- LeetCode-Algorithm2 C++的链表
- leetcode algorithm2 add two number
- leetcode的C语言表述
- [C++]LeetCode: 108 Add Two Numbers (反序链表求和)
- [C++]LeetCode: 125 Sort List (归并排序链表)
- [C++]LeetCode: 126 Insertion Sort List (插入排序链表)
- paper3—Algorithm2-Engine-Trigger-on-SMD—temp
- paper3—Algorithm2-Engine-Trigger-on-SMD—temp
- Algorithm2——斐波那契数列
- LeetCode上twoSums的C语言代码
- Leetcode 删除重复的链表元素
- 【leetcode】链表的基本操作
- leetcode-异形链表的深度拷贝
- leetcode 第二题:链表的使用
- leetcode 21. Merge Two Sorted Lists(C语言,合并两个排序的链表为一个排序链表)32
- c的链表
- 复杂链表的复制(C/C++)
- [C/C++]链表的连接
- 软件测试-学习笔记(一)
- 算法训练 方格取数
- Java 封装
- 反射拿到该类的实例对象
- T-SQL语句整理
- LeetCode-Algorithm2 C++的链表
- 宏汇编实现字母大小写的转换
- struts2_09_动态结果集
- java中常见的几种排序方式
- Fibonaccci数列
- 164. Maximum Gap
- java:懂二进制
- 进程和线程的区别
- 速度飞跃——关系型数据库到非关系型数据库