add two linked list as integer
来源:互联网 发布:tcss.ping.js 编辑:程序博客网 时间:2024/06/05 16:03
Question:
You have two numbers represented by a linked list, where each node contains a single digit. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE:
input: (3 -> 1 -> 5), (5 -> 9 -> 2)output: 9 -> 0 -> 7
Analyze:
use two stacks to store the numbers in the list, and then the last number of the lists will be on the top of the stacks, we pop the stack and add the numbers, and save the result into the linked list.
Code:
public static LinkedList addList(Node h1, Node h2) {//save the numbers in the list to stacksStack<Node> s1 = new Stack<Node>();Stack<Node> s2 = new Stack<Node>();while(h1 != null) {s1.push(h1);h1 = h1.next;}while(h2 != null) {s2.push(h2);h2 = h2.next;}//LinkedList saves the resultLinkedList list = new LinkedList();int sum = 0;int carry = 0;while(!s1.empty() && !s1.empty()) {sum = s1.pop().data + s2.pop().data + carry;carry = sum / 10;sum = sum % 10;list.addFirst(sum);}while(!s1.empty()) {sum = s1.pop().data + carry;carry = sum / 10;sum = sum % 10;list.addFirst(sum);}while(!s2.empty()) {sum = s1.pop().data + carry;carry = sum / 10;sum = sum % 10;list.addFirst(sum);}// don't forget the carryif (carry != 0) list.addFirst(carry);return list;}http://blog.csdn.net/beiyetengqing
- add two linked list as integer
- add two linked list as integer
- [CrackCode] 2.4 Add two numbers and return the sum as a linked list
- 2. Add Two Numbers(Linked List)
- The two numbers and return it as a linked list
- Linked List -- Leetcode problem 2. Add Two Numbers
- 【Linked-list专题-1】445. Add Two Numbers II 328. Odd Even Linked List
- Merge Two Linked List
- 【12】Adds two numbers represented by a linked list and returns the sum as a linked list
- LeetCode(四)链表206. Reverse Linked List&2. Add Two Numbers
- leetcode Merge Two Linked List
- Intersection of Two Linked List
- Intersection Of Two Linked List
- Merge two sorted linked list
- Leetcode - List - Add Two Numbers
- Add two numbers-list,string
- [leetcode][list] Add Two Numbers
- [leetcode][list] Add Two Numbers
- ZJUT 1277 素数的位数和 (不是水题胜似水题)
- 有时候,我想消失一下,然后看看是否会有人想念我
- 更新到WordPress 3.1后Custom Fields消失?
- 软件设计模式之模拟游角色选择(Darren建造者模式)
- 【Andorid应用开发】-(2)Linux、Windows开发环境配置
- add two linked list as integer
- 菜鸟进阶必杀技(Ⅱ)——java基础知识自测篇
- 认识StringBuilder的Capacity自动增加方式
- Linux下开启/关闭MySql Server
- C++类的存储结构
- python的包实现机制
- Python IDE比较与推荐
- 悲守穷庐,将复何及
- java synchronized详解