You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output: 7, 0, 8
Answer:
/**
* 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) {
If the L1 is null,l2 not NULL, it is returned directly L2
if (l1==null&&l2!=null)
{
return L2;
}
If the L2 is NULL,L1 not NULL, it is returned directly L1
else if (l1!=null&&l2==null)
{
return L1;
}
If L1 is null for NULL,L2, NULL is returned directly
else if (l1==null&&l2==null)
{
return null;
}
Else
{
Store the data in the results
Create a new node, at the beginning of it 0
ListNode head=new listnode (0);
Give this node to result
ListNode Result=head;
int jinwei=0;
To simulate the addition yourself
If none of the two linked lists have reached the end
while (L1!=null&&l2!=null)
{
if (l1.val+l2.val+jinwei<10)
{
ListNode temp=new ListNode (L1.val+l2.val+jinwei);
Rounding is 0
jinwei=0;
Move the result value back one step
Head.next=temp;
Head=head.next;
One step after each addend
L1=l1.next;
L2=l2.next;
}
Else
{
ListNode temp=new ListNode (l1.val+l2.val+jinwei-10);
Rounding is 0
Jinwei=1;
Move the result value back one step
Head.next=temp;
Head=head.next;
One step after each addend
L1=l1.next;
L2=l2.next;
}
}
If L1 is not at the end, L2 to the end.
if (l1!=null)
{
while (L1!=null)
{
if (l1.val+jinwei<10)
{
ListNode temp=new ListNode (L1.val+jinwei);
Rounding is 0
jinwei=0;
Move the result value back one step
Head.next=temp;
Head=head.next;
One step after each addend
L1=l1.next;
}
Else
{
ListNode temp=new ListNode (l1.val+jinwei-10);
Rounding is 0
Jinwei=1;
Move the result value back one step
Head.next=temp;
Head=head.next;
One step after each addend
L1=l1.next;
}
}
}
If L2 doesn't end, but L1 reaches the end.
if (l2!=null)
{
while (L2!=null)
{
if (l2.val+jinwei<10)
{
ListNode temp=new ListNode (L2.val+jinwei);
Rounding is 0
jinwei=0;
Move the result value back one step
Head.next=temp;
Head=head.next;
One step after each addend
L2=l2.next;
}
Else
{
ListNode temp=new ListNode (l2.val+jinwei-10);
Rounding is 0
Jinwei=1;
Move the result value back one step
Head.next=temp;
Head=head.next;
One step after each addend
L2=l2.next;
}
}
}
Examine the final rounding.
if (jinwei!=0)
{
ListNode temp=new ListNode (1);
Move the result value back one step
Head.next=temp;
Head=head.next;
}
return result.next;
}
}
}
Leetcode of Practice Programming----------(2) ADD-Numbers