LintCode-两个链表的和
2015-10-04 19:50
337 查看
容易 两个链表的和
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。样例
给出两个链表
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) { ListNode l3=new ListNode(0); ListNode l =l3; boolean run=true; int flag=0; do{ int k=l1.val+l2.val+flag; flag=(int)k/10; k=k%10; l3=l3.next=new ListNode(k); if(l1.next==null&&l2.next==null){ run=false; if(flag!=0){ l3.next=new ListNode(flag); } } if(l1.next!=null){ l1=l1.next; }else{ l1.val=0; } if(l2.next!=null){ l2=l2.next; }else{ l2.val=0; } }while(run); return l.next; } }
一个很简单的遍历。
相关文章推荐
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- LintCode 翻转二叉树
- LintCode 寻找缺失的数
- Lintcode 比较字符串
- Lintcode 主元素
- Lintcode解题笔记 - 岛屿的个数
- LintCode -合并两个排序链表
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- 20150708 lintcode 总结 Minimum Path Sum
- 20150708 lintcode 总结 Binary Search Tree Iterator
- 20150707 lintcode 总结 Search Range in Binary Search Tree
- 20150624 lintcode 总结 binary-tree-level-order-traversal **
- 20150624 lintcode 总结 Lowest Common Ancestor
- 20150624 lintcode 总结 Balanced Binary Tree
- Lintcode(1)-两个字符串是变位词