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

解题思路:

定义三个ListNode l1、l2,result,其中result为return语句的输出,l1、l2为传入的参数。

将l1赋值给result,执行result.val+=l2.val,然后l1作为指针一级一级往下走,直到走到l2.next为null。当然,之间会有不少边界条件,自己debug一下就好。

Java代码如下:

public class Solution {
static public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result=l1;
while(true){
l1.val+=l2.val;
if(l1.val>=10){
l1.val%=10;
if(l1.next==null) l1.next=new ListNode(1);
else l1.next.val+=1;
} if(l2.next==null){
ListNode l3=l1.next;
while(true){
if (l3==null) break;
if(l3.val==10){
l3.val%=10;
if(l3.next==null) l3.next=new ListNode(1);
else l3.next.val+=1;
}
l3=l3.next;
}
break;
} l2=l2.next;
if(l1.next==null){
l1.next=new ListNode(0);
}
l1=l1.next;
}
return result; }
}

C++

 class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* res=l1;
while (true) {
l1->val += l2->val;
if (l1->val >= ) {
l1->val %= ;
if (l1->next == NULL)
l1->next = new ListNode();
else l1->next->val += ;
} if (l2->next == NULL) {
ListNode* l3 = l1->next;
while (true) {
if (l3 == NULL) break;
if (l3->val == ) {
l3->val %= ;
if (l3->next == NULL) l3->next = new ListNode();
else l3->next->val += ;
}
l3 = l3->next;
}
break;
} l2 = l2->next;
if (l1->next == NULL) {
l1->next = new ListNode();
}
l1 = l1->next;
}
return res;
}
};

最新文章

  1. python处理空格脚本
  2. 【转】深入理解 Java 垃圾回收机制
  3. monodevelop 突然莫名其妙的将 warning 全部标记为 error
  4. python 学习笔记12(序列常用方法总结)
  5. [Linux]yum开启rpm包缓存
  6. PHP如何批量生成手机号-使用PHP 如何生成一组不重复的手机号码?
  7. 奇怪的梦境(codevs 2833)
  8. 刚刚学了循环,1到n的求和与阶乘
  9. Quartz.net一个简要示例
  10. 在shell中通过fifo与服务器交互
  11. Spring(3.2.3) - Beans(12): 属性占位符
  12. oracle 字段上下两条记录的相减
  13. ASP.NET如何发布更新
  14. ueditor asp.net版本更改图片保存路径
  15. Windows下命令(bat可用)
  16. TensorFlow官方文档
  17. java中打开文件流后要关闭后重新打开
  18. C++ assert断言
  19. python网络爬虫抓取网站图片
  20. 理解RHEL上安装oracle的配置参数 :/etc/security/limits.conf, /etc/profile, /etc/pam.d/login

热门文章

  1. 【BZOJ-1452】Count 树状数组 套 树状数组
  2. 洛谷P1203 [USACO1.1]坏掉的项链Broken Necklace
  3. groovy-输入输出
  4. SpringMVC 2.5.6 noMapping
  5. 修改host
  6. JAVA实现DES加密实现详解
  7. 百度文库,linux下安装oracle客户端
  8. Run UliPad 4.1 Under Windows 7 64bit and wxPython 3.0.2
  9. jquery 调用数据
  10. 不用插件直接同步wordpress文章日志到新浪微博