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;

代码:

 /**
* 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();
ListNode* newlist = preheader;
int flag = ; while (l1 || l2) {
int sum = flag;
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
} flag = sum / ;
sum = sum % ;
newlist->next = new ListNode(sum);
newlist = newlist->next;
} if (flag)
newlist->next = new ListNode(flag); return preheader->next;
}
};

最新文章

  1. git学习之冲突解决办法
  2. Spring为某个属性注入值或为某个方法的返回值
  3. PHP获取远程图片并调整图像大小(转)
  4. hdu 2177 取(2堆)石子游戏 博弈论
  5. 使用Java VisualVM监控远程JVM
  6. HDU-4737 A Bit Fun 维护
  7. Java多线程初学者指南(5):join方法的使用
  8. Duplex Service in WCF(CodeProject上的)
  9. 让Barebox正确引导Tiny6410的linux内核
  10. poj2409 Let it Bead
  11. C# 堆栈和堆 Heap & Stack
  12. Codeforces 1092C Prefixes and Suffixes(思维)
  13. JQ01
  14. [20180718]拷贝数据文件从dg库.txt
  15. MySQl中的\g和\G
  16. 【原】MySQL实用SQL积累
  17. sql2008 安装提示重启失败
  18. 从12306网站新验证码看Web验证码设计与破解
  19. 基于FPGA的HDMI显示设计(三)
  20. Install nginx on ubuntu

热门文章

  1. redis有序集合类型sort set
  2. js跳出循环:break 、continue 、return
  3. 如何快速将文本中的tab更换成逗号(图文详解)
  4. Logback 学习笔记
  5. 我与ARM的那些事儿1初识ARM
  6. iOS傻金币动画
  7. android 使用图片轮播图---banner 使用
  8. Best MVC Practices 最佳的MVC实践
  9. Java学习--Jsp简介
  10. 四、cent OS安装配置mysql