您的位置:首页 > 其它

Cracking the coding interview--Q2.4

2014-02-04 23:40 357 查看
题目

原文:

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

译文:

你有两个由单链表表示的数,每个节点包含一个单独的数,这些数是被倒序存储的,也就是说各位位于表头,写一个函数实现这两个数的相加,并用链表的形式返回它们的和。

例如

输入:(3->1->5), (5->9->2)

输出:8->0->8

解答

注意一些特殊情况:a.链表为空;b.有进位;c.长度不一,代码如下:

class Q2_4{

public static LinkList addList(LinkList ll1,LinkList ll2){
LinkList<Integer> ll=new LinkList<Integer>();
Node<Integer> node1=ll1.head;
Node<Integer> node2=ll2.head;
int one=0;
if(node1==null) return ll2;
if(node2==null) return ll1;
while(node1!=null&&node2!=null){
int value=node1.getData()+node2.getData()+one;
if(value>=10){
ll.add(value%10);
one=1;
}else{
ll.add(value);
one=0;
}
node1=node1.getNext();
node2=node2.getNext();
}
while(node1!=null) {
ll.add(one+node1.getData());
node1=node1.getNext();
one=0;
}
while(node2!=null){
ll.add(one+node2.getData());
node2=node2.getNext();
one=0;
}
return ll;
}
public static void main(String[] args){
int[] data1=new int[]{};
int[] data2=new int[]{5,9,2};
LinkList<Integer> ll1=new LinkList<Integer>();
LinkList<Integer> ll2=new LinkList<Integer>();
for(int i=0;i<data1.length;i++){
ll1.add(data1[i]);
}
for(int i=0;i<data2.length;i++){
ll2.add(data2[i]);
}

addList(ll1,ll2).print();
}
}

class Node<T>{
public T data;
public Node<T> next;

public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
}

class LinkList<T>{
public Node<T> head;
public Node<T> tail;
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}

public void add(T i){

//在链表结尾插入节点
Node<T> newnode = new Node<T>();
newnode.setData(i);
if(head == null){
head = newnode;
tail = newnode;
size ++ ;
}
else {
tail.setNext(newnode);
tail = newnode;
size ++ ;
}
}

public void print(){
if(head == null){
System.out.println("链表为空");
return;
}
Node<T> temp = head;
while(temp.getNext()!= null){
System.out.print(temp.getData().toString());
temp=temp.getNext();
}
System.out.println(temp.getData().toString());
}
}


此题如有更好的方法,还望指教!
---EOF---
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: