表示数字的链表

时间:2017-01-27 15:14:16

标签: java linked-list

我有一个看起来像这样的IntNode类:

public class IntNode {
private int value;
private IntNode next;
public IntNode(int val, IntNode n)
{
    value = val;
    next = n;
}
public void setValue(int val){ value = val; }
public void setNext(IntNode n){ next = n; }
public int getValue() { return value; }
public IntNode getNext() { return next; }
}

和另一个我把它命名为BigNumber的类,它应该代表任何正数(大或小)。该课程如下:

public class BigNumber {

private IntNode list;
    //copy constructor.
public BigNumber(BigNumber other){
    list = null;
    for(IntNode p=other.list; p!=null; p=p.getNext())
        list = new IntNode(p.getValue(), list);
}

    //Constructor that takes string of a number and puts every digit in the linked list. if the string contains any char that is not digit, the linked list should be: 0->null.
public BigNumber(String num){
    list = null;
    if(stringIsNum(num)){
        for(int i=0; i<num.length(); i++){
            list = new IntNode((int)num.charAt(i),list);
        }
    }
    else{
        list = new IntNode(0, list);
    }
}

private boolean stringIsNum(String num){
    for(int i=0; i<num.length(); i++){
        if(!(num.charAt(i)>='0' && num.charAt(i)<='9'))
            return false;
    }
    return true;
}

public String toString(){
    String s = "";
    for(IntNode p=list; p!=null; p=p.getNext())
        s+=p.getValue()+"";
    return s;   
}
}

这个类中的问题是,当我想要打印时,假设字符串是“123”,它打印的内容类似于515049,而不是实际的数字是321,(它应该向后打印数字)。 有什么问题?

2 个答案:

答案 0 :(得分:1)

您正在将char转换为int。这给出了char的代码点,而不是您想要的值。例如:(int)&#39; 1&#39; = 49

而不是(int)num.charAt(i)使用Integer.parseInt(num.charAt(i))

答案 1 :(得分:1)

获得321. 51,50和49是3,2和1的char值。您的代码是保存char值而不是实际值。换句话说,你很接近,只需要保存正确的值。

相关问题