Add Two number in Linked(forward order)
2014-02-26 02:49
281 查看
public static ListNode add(ListNode l1, ListNode l2){ Stack<Integer> s1 = new Stack<Integer>(); Stack<Integer> s2 = new Stack<Integer>(); while(l1!=null){ s1.push(l1.val); l1 = l1.next; } while(l2!=null){ s2.push(l2.val); l2 = l2.next; } int carry = 0; ListNode safe = new ListNode(-1); ListNode p = safe.next; while(!s2.isEmpty() &&!s1.isEmpty()){ int d1 = s1.pop(); int d2 = s2.pop(); safe.next = new ListNode((d1+d2+carry)%10); safe.next.next = p; p=safe.next; carry = (d1+d2)/10; } while(!s1.isEmpty()){ int d1 = s1.pop(); safe.next = new ListNode((d1+carry)%10); safe.next.next = p; p = safe.next; carry = (d1+carry)/10; } while(!s2.isEmpty()){ int d2 = s2.pop(); safe.next = new ListNode((d2+carry)%10); safe.next.next = p; p = safe.next; carry = (carry+d2)/10; } if(carry>0){ safe.val = carry; return safe; } else return safe.next; }
View Code
相关文章推荐
- CheckPalindrom int LinkedList
- 编译安装apache
- Linux中文件查找——find命令 推荐
- Apache Prefork、Worker和Event三种MPM
- Call to undefined function mb_detect_encoding()错误的处理方法
- window7使用windows Live Write来写51CTO博客
- mysql_connect报告”No such file or directory”错误的解决方法
- Access denied for user 'root'@'localhost' (using password: YES)
- 网站许久不管为什么排名越来越好
- Stanford - Cryptography I - Week 1-1 Programming Assignment
- hdoj1001--Sum Problem
- codeforces#231_div2_B Very Beautiful Number 高精度枚举
- codeforces#231_div2_B Very Beautiful Number 高精度枚举
- LeetCode - Gas Station
- Linux yum仓库的安装
- java面试题---算法2
- 面试题
- uboot源码中start.S里中断向量表中不直接LDR PC ,"异常地址",而是使用一个标号
- ldr和adr在使用标号表达式作为操作数的区别
- java算法面试题-----1