链表求和II
2017-06-22 21:37
211 查看
假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
样例
给出 6->1->7 + 2->9->5。即,617 + 295。
返回 9->1->2。即,912 。
样例
给出 6->1->7 + 2->9->5。即,617 + 295。
返回 9->1->2。即,912 。
import java.util.Scanner; import java.util.Stack; /** * 假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。 样例 给出 6->1->7 + 2->9->5。即,617 + 295。 返回 9->1->2。即,912 。 * * @author Dell * */ public class Test221 { public static ListNode addLists2(ListNode l1,ListNode l2) { if(l1==null) return l2; if(l2==null) return l1; Stack<Integer> s1=new Stack<>(); Stack<Integer> s2=new Stack<>(); Stack<Integer> s3=new Stack<>(); ListNode result=new ListNode(-1); ListNode p=l1; ListNode q=l2; ListNode r=result; while(p!=null) { s1.push(p.val); p=p.next; } while(q!=null) { s2.push(q.val); q=q.next; } int c=0; while(s1.isEmpty()!=true&&s2.isEmpty()!=true) { int a=s1.pop(); int b=s2.pop(); int d=a+b; if(c==1) { d++; c=0; } if(d>=10) { d=d-10; c=1; } s3.push(d); } while(s1.isEmpty()!=true) { int a=s1.pop(); if(c==1) { a++; c=0; } if(a>=10) { a=a-10; c=1; } s3.push(a); } while(s2.isEmpty()!=true) { int a=s2.pop(); if(c==1) { a++; c=0; } if(a>=10) { a=a-10; c=1; } s3.push(a); } if(c==1) { s3.push(1); } while(s3.isEmpty()!=true){ ListNode temp=new ListNode(s3.pop()); r.next=temp; r=r.next; } return result.next; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n1=sc.nextInt(); int n2=sc.nextInt(); ListNode list1=new ListNode(-1); ListNode p=list1; for(int i=0;i<n1;i++) { ListNode temp=new ListNode(sc.nextInt()); p.next=temp; p=p.next; } ListNode list2=new ListNode(-1); ListNode q=list2; for(int i=0;i<n2;i++) { ListNode temp=new ListNode(sc.nextInt()); q.next=temp; q=q.next; } ListNode result=addLists2(list1.next,list2.next); while(result!=null) { System.out.print(result.val); result=result.next; } } }
相关文章推荐
- 221 - 链表求和 II
- lintcode(221)链表求和 II
- 链表求和 II-LintCode
- lintcode-221-链表求和 II
- 链表求和 II
- LintCode-[中等] 221. 链表求和 II
- leetcode 82-- Remove Duplicates from Sorted List II 链表 双指针 删除元素
- LeetCode 364. Nested List Weight Sum II 嵌套链表权重和之二
- 链表求和
- Leetcode#142(链表)-Linked List Cycle II
- LintCode-----36.翻转链表 II
- 【LeetCode题解】142_环形链表2(Linked-List-Cycle-II)
- leetcode 92. Reverse Linked List II 反转链表 + 头插入反转链表(或者使用栈)
- 区间求和 II -LintCode
- leetcode_c++:链表:Linked List Cycle II(142)
- 翻转链表 II
- LeetCode | Populating Next Right Pointers in Each Node II(将每一层链接成一个链表)
- Lintcode167.链表求和C++
- lintcode--带环链表II
- 链表求和