LeetCode 445. Add Two Numbers II
来源:互联网 发布:cmd查询数据库 编辑:程序博客网 时间:2024/06/01 07:34
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { //用两个栈分别存放l1和l2的元素,然后对应相加 Stack<Integer> stack1=new Stack<Integer>(); Stack<Integer> stack2=new Stack<Integer>(); ListNode p=l1,q=l2; ListNode head=new ListNode(0); while(p!=null){ stack1.push(p.val); p=p.next; } while(q!=null){ stack2.push(q.val); q=q.next; } //将相同长度部分加起来,进位carry int carry=0; int temp_val=stack1.pop()+stack2.pop(); ListNode r=new ListNode(temp_val%10); if(temp_val>=10) { carry=1; }else{ carry=0; } while(!stack1.empty() && !stack2.empty()){ temp_val=stack1.pop()+stack2.pop()+carry; ListNode temp=new ListNode(temp_val%10); temp.next=r; r=temp; if(temp_val>=10) { carry=1; }else{ carry=0; } } while(!stack1.empty()){ temp_val=stack1.pop()+carry; ListNode temp=new ListNode(temp_val%10); temp.next=r; r=temp; if(temp_val>=10){ carry=1; }else{ carry=0; } } while(!stack2.empty()){ temp_val=stack2.pop()+carry; ListNode temp=new ListNode(temp_val%10); temp.next=r; r=temp; if(temp_val>=10){ carry=1; }else{ carry=0; } } if(carry>0){ ListNode temp=new ListNode(carry); temp.next=r; r=temp; } return r; }}
0 0
- LeetCode 445. Add Two Numbers II
- leetcode-445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- [LeetCode]445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- 【LeetCode】 445. Add Two Numbers II
- LeetCode笔记:445. Add Two Numbers II
- leetcode 445. Add Two Numbers II
- 【Leetcode】445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- Leetcode-445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- leetcode 445. Add Two Numbers II
- leetcode 445. Add Two Numbers II
- [LeetCode] 445. Add Two Numbers II
- [LeetCode]445. Add Two Numbers II
- 音频涉及的相关概念
- a++ 与++a在内存中的正确姿势
- nc 的缺点
- SSM杰信商务平台项目day08
- 利用OpenCV进行图像匹配
- LeetCode 445. Add Two Numbers II
- Oil Deposits HDU
- Linux内核学习总结
- QT调用编辑caffe c++ API
- poj 2155 Matrix
- 抽象类细节及使用方法
- HDU2066
- Navicat常用快捷键
- 机器学习-实战-入门-MNIST手写数字识别