您的位置:首页 > 编程语言 > Java开发

leetcode 2. Add Two Numbers

2017-05-11 14:50 417 查看
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

/**
* 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) {
ListNode p=l1,q=l2;
ListNode head=new ListNode(-1);
ListNode hp=head;
int plus=0;
int carry=0;
while(p!=null&&q!=null){
plus=p.val+q.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
p=p.next;
q=q.next;
}
while(p!=null){
plus=p.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
p=p.next;
}
while(q!=null){
plus=q.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
q=q.next;
}
if(carry!=0){
ListNode ln=new ListNode(carry);
ln.next=null;
hp.next=ln;
hp=ln;

}
return head.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息