您的位置:首页 > 其它

【12】Adds two numbers represented by a linked list and returns the sum as a linked list

2013-04-15 23:14 423 查看
Question:You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the
1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.EXAMPLE Input: (3 -> 1 -> 5), (5 -> 9 -> 2) Output: 8 -> 0 -> 8

package CareerCup;

public class AddLists
{
public AddLists(){}
public LinkedList add(LinkedList l1, LinkedList l2)
{
LinkedList res = new LinkedList();
Node header1 = l1.header;
Node header2 = l2.header;
int addmore = 0;
while(!(l1.header==null && l2.header==null))
{
int value = addmore;
if(l1.header!=null) value += l1.header.data;
if(l2.header!=null) value += l2.header.data;
addmore = value/10;
value %= 10;
res.add(value);
l1.deleteHead();
l2.deleteHead();
}
if(addmore!=0) res.add(addmore);
return res;
}

public static void main(String[] args)
{
int[] data1 = new int[]{3,1,5};
int[] data2 = new int[]{5,9,2};
LinkedList ll1 = new LinkedList();
LinkedList ll2 = new LinkedList();
for(int i=0;i<data1.length;i++)
ll1.add(data1[i]);
for(int i=0;i<data2.length;i++)
ll2.add(data2[i]);
System.out.println("The linkedlist1:");
ll1.print();
System.out.println("The linkedlist2:");
ll2.print();
AddLists ad = new AddLists();
LinkedList llsum = ad.add(ll1, ll2);
System.out.println("The linkedlist sum:");
llsum.print();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐