add two linked list as integer
来源:互联网 发布:linux登录mysql 编辑:程序博客网 时间:2024/06/07 00:54
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/beiyeqingteng
- 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
- Android中集成第三方软件包(.jar, .so)
- 使用nginx后如何在web应用中获取用户ip及原理解释
- merge two sorted linked list with duplicates
- 课程设计
- Android 关于android:name属性问题
- add two linked list as integer
- 【基础C&C++】内联函数&宏定义
- 用脚本建库ASM+单节点(增加节点,横向扩展RAC节点)步骤
- cscope+Vim的简单配置
- 使用NSTimer与iphone的简单动画,实现飘雪效果
- div
- MYsql 主从双向同步
- vs2008 使用c#编写web浏览器加载的windows窗体控件
- Android 关于所谓的“深度睡眠”的问题