Java实现-链表求和2
2017-06-24 10:22
239 查看
假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字
您在真实的面试中是否遇到过这个题?
Yes
样例
给出
返回
顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出
6->1->7+
2->9->5。即,
617 + 295。
返回
9->1->2。即,
912。
/** * 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 addLists2(ListNode l1, ListNode l2) { // write your code here if(l1==null){ return l2; } if(l2==null){ return l1; } Stack<ListNode> stack1=new Stack<ListNode>(); while(l1!=null){ ListNode node=l1; l1=l1.next; node.next=null; stack1.add(node); } Stack<ListNode> stack2=new Stack<ListNode>(); while(l2!=null){ ListNode node=l2; l2=l2.next; node.next=null; stack2.add(node); } ListNode dummy=new ListNode(-1); int carry=0; while(!stack1.isEmpty()&&!stack2.isEmpty()){ ListNode node1=stack1.pop(); ListNode node2=stack2.pop(); int temp=node1.val+node2.val+carry; ListNode s=new ListNode(temp%10); if(temp>9){ carry=1; if(dummy.next==null){ dummy.next=s; }else{ ListNode node=dummy.next; s.next=node; dummy.next=s; } }else{ carry=0; if(dummy.next==null){ dummy.next=s; }else{ ListNode node=dummy.next; s.next=node; dummy.next=s; } } } if(stack1.isEmpty()){ while(!stack2.isEmpty()){ ListNode node2=stack2.pop(); int temp=carry+node2.val; ListNode s=new ListNode(temp%10); if(temp>9){ ListNode node=dummy.next; s.next=node; dummy.next=s; carry=1; }else{ ListNode node=dummy.next; s.next=node; dummy.next=s; carry=0; } } } if(stack2.isEmpty()){ while(!stack1.isEmpty()){ ListNode node1=stack1.pop(); int temp=carry+node1.val; ListNode s=new ListNode(temp%10); if(temp>9){ ListNode node=dummy.next; s.next=node; dummy.next=s; carry=1; }else{ ListNode node=dummy.next; s.next=node; dummy.next=s; carry=0; } } } if(carry==1){ ListNode s=new ListNode(1); ListNode node=dummy.next; s.next=node; dummy.next=s; return dummy.next; }else{ return dummy.next; } } }
相关文章推荐
- 一元多项式求和(Java链表实现)
- 【LintCode-167】链表求和(Java实现)
- 使用JAVA实现双向链表
- JAVA实现双向链表
- 利用链表实现队列的Java代码
- Java实现链表
- Java实现链表
- Java语言中链表和双向链表的实现
- Java数据结构之简单链表的定义与实现方法示例
- JAVA实现链表
- java 单向链表的实现
- java链表实现约瑟夫算法
- Java 实现 链表
- Java语言中链表和双向链表的实现
- JAVA 语言中链表和双向链表的实现
- 某一天的思考题(使用Java实现链表)的参考答案
- java 语言中链表和双向链表的实现!
- Java语言中链表和双向链表的实现-Java基础-Java-编程开发
- Java 用单链表实现多项式加减乘
- 用java数组实现基本链表和可自扩充的链表