标签:
You are given two linked lists representing two non-negative numbers. 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.
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;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//如果l1为null,l2不为null的话,则直接返回l2
if(l1==null&&l2!=null)
{
return l2;
}
//如果l2为null,l1不为null的话,则直接返回l1
else if(l1!=null&&l2==null)
{
return l1;
}
//如果l1为null,l2为null的话,则直接返回null
else if(l1==null&&l2==null)
{
return null;
}
else
{
//把数据存放到结果中去
//新建一个节点,一开始的时候它0
ListNode head=new ListNode(0);
//把这个节点给result
ListNode result=head;
int jinwei=0;
//自己对加法进行模拟
//如果两个链表都没有到结尾
while(l1!=null&&l2!=null)
{
if(l1.val+l2.val+jinwei<10)
{
ListNode temp=new ListNode(l1.val+l2.val+jinwei);
//进位为0
jinwei=0;
//结果值后移一步
head.next=temp;
head=head.next;
//每一个加数后移一步
l1=l1.next;
l2=l2.next;
}
else
{
ListNode temp=new ListNode(l1.val+l2.val+jinwei-10);
//进位为0
jinwei=1;
//结果值后移一步
head.next=temp;
head=head.next;
//每一个加数后移一步
l1=l1.next;
l2=l2.next;
}
}
//如果l1没到结尾,l2到结尾的话
if(l1!=null)
{
while(l1!=null)
{
if(l1.val+jinwei<10)
{
ListNode temp=new ListNode(l1.val+jinwei);
//进位为0
jinwei=0;
//结果值后移一步
head.next=temp;
head=head.next;
//每一个加数后移一步
l1=l1.next;
}
else
{
ListNode temp=new ListNode(l1.val+jinwei-10);
//进位为0
jinwei=1;
//结果值后移一步
head.next=temp;
head=head.next;
//每一个加数后移一步
l1=l1.next;
}
}
}
//如果l2没到结尾,但是l1到达结尾的话
if(l2!=null)
{
while(l2!=null)
{
if(l2.val+jinwei<10)
{
ListNode temp=new ListNode(l2.val+jinwei);
//进位为0
jinwei=0;
//结果值后移一步
head.next=temp;
head=head.next;
//每一个加数后移一步
l2=l2.next;
}
else
{
ListNode temp=new ListNode(l2.val+jinwei-10);
//进位为0
jinwei=1;
//结果值后移一步
head.next=temp;
head=head.next;
//每一个加数后移一步
l2=l2.next;
}
}
}
//考察最后的进位
if(jinwei!=0)
{
ListNode temp=new ListNode(1);
//结果值后移一步
head.next=temp;
head=head.next;
}
return result.next;
}
}
}
练习编程之leetcode篇----------(2)Add Two Numbers
标签:
原文地址:http://www.cnblogs.com/bjzhang-nju/p/4404639.html