链表求和
来源:互联网 发布:淘宝有卖寿衣 编辑:程序博客网 时间:2024/05/19 20:20
链表求和
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反
的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例
给出两个链表 3->1->5->null
和 5->9->2->null
,返回8->0->8->null
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { /** * @param l1: the first list * @param l2: the second list * @return: the sum list of l1 and l2 */ public ListNode addLists(ListNode l1, ListNode l2) { // write your code here ListNode root=null,cur=null; int flag = 0; while(l1 !=null && l2!=null){ int val = l1.val + l2.val +flag; flag = val / 10; val = val % 10; ListNode temp = new ListNode(val); if(root == null){ root = temp; } if(cur != null){ cur.next = temp; } cur = temp; l1 = l1.next; l2 = l2.next; } while(l1 != null){ int val = l1.val + flag; flag = val / 10; val %= 10; ListNode temp = new ListNode(val); if(root == null){ root = temp; } if(cur != null){ cur.next = temp; } cur = temp; l1 = l1.next; } while(l2 != null){ int val = l2.val + flag; flag = val / 10; val %= 10; ListNode temp = new ListNode(val); if(root == null){ root = temp; } if(cur != null){ cur.next = temp; } cur = temp; l2 = l2.next; } if(flag == 1){ ListNode temp = new ListNode(flag); cur.next = temp; } return root; }}
0 0
- 链表求和 & 二进制求和
- 链表多项式求和
- 链表求和
- LintCode 链表求和
- 链表求和
- lintcode ----链表求和
- 链表求和
- 链表求和
- 链表求和
- 链表求和
- 链表求和
- 链表求和
- 链表求和
- 链表求和
- LintCode 链表求和
- 链表求和-LintCode
- 链表求和
- 链表求和
- chrome input输入框黄色背景去除
- 给职场新人的10点职涯建议
- 97.Which statement is true about loading data using the conventional path of SQL*Loader?
- Ubunut服务器搭建Node服务
- apache2.2 prefork模式优化
- 链表求和
- Java JVM:编译加载与自定义类加载器
- js按照相同日期再组装数组
- Matlab中矩阵的归一化和正交化函数
- 链表笔面问题
- SAP HANA视频资料分享
- apache中显示目录列表
- redis3.0.0 集群安装详细步骤
- 你不太了解的观止云分发(之一):多协议回源、边缘转封装、动态配置