【Leetcode】【Medium】Add Two Numbers
2015-06-24 02:59
288 查看
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
本题特点:
1、链表已经是倒序的,因此首结点就是个位数字;
解题步骤:
1、建立preHead结点,指向新链表表头,新链表记录加法结果;(注意新建链表,不要在原链表上操作)
2、新建整形flag,记录进位;
3、开始循环操作,只要L1和L2有一个不为空,循环继续:
(1)新建临时整形sum,初始值为flag;
(2)L1不为空,则加上L1的值;L2不为空,则加上L2的值;
(3)flag = sum / 10; sum = sum % 10;
(4)记录在新建链表上;
4、如果flag还存在值,则再新建一个结点;
5、记录preHead->next地址head,delete preHead,返回head;
代码:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
本题特点:
1、链表已经是倒序的,因此首结点就是个位数字;
解题步骤:
1、建立preHead结点,指向新链表表头,新链表记录加法结果;(注意新建链表,不要在原链表上操作)
2、新建整形flag,记录进位;
3、开始循环操作,只要L1和L2有一个不为空,循环继续:
(1)新建临时整形sum,初始值为flag;
(2)L1不为空,则加上L1的值;L2不为空,则加上L2的值;
(3)flag = sum / 10; sum = sum % 10;
(4)记录在新建链表上;
4、如果flag还存在值,则再新建一个结点;
5、记录preHead->next地址head,delete preHead,返回head;
代码:
/** * 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* preheader = new ListNode(0); ListNode* newlist = preheader; int flag = 0; while (l1 || l2) { int sum = flag; if (l1) { sum += l1->val; l1 = l1->next; } if (l2) { sum += l2->val; l2 = l2->next; } flag = sum / 10; sum = sum % 10; newlist->next = new ListNode(sum); newlist = newlist->next; } if (flag) newlist->next = new ListNode(flag); return preheader->next; } };
相关文章推荐
- HDU 4622 Reincarnation
- Xming + PuTTY 在Windows下远程Linux主机
- Xming + PuTTY 在Windows下远程Linux主机
- Codeforces Round #306 (Div. 2) 题解
- tomcat - set up username and password
- post 传字典
- 笔记-Microsoft SQL Server 2008技术内幕:T-SQL语言基础-10 可编程对象
- dedecms调用子栏目内容,缩略图,以及栏目名字
- hdu 2680 Choose the best route
- swift版本hello
- 直方图均衡化原理之概率论相关知识
- iOS-图片的拉伸
- 加载3D模型时注意事项
- Qt热点
- Ubuntu12.04下WiFi热点配置
- jQuery选择器
- E: Unable to correct problems, you have held broken packages.
- linux 的有用的网站
- HDU 4622 求解区间字符串中的不同子串的个数
- nodeJS链接mysql数据库(express框架)