反转字符的字符串顺序,并使用构造函数放置到LinkedList中

时间:2019-03-06 23:50:40

标签: java string debugging linked-list

我正在编写一个程序,该程序接受一个String并将其以相反的顺序放入LinkedList中。

此代码似乎无效(输入错误),我也不知道为什么。有解决方案吗?

public LargeInteger(String input) 
{
     TODO
    size=size+input.length();
    LLNode<Integer> curNode=new LLNode<Integer>();
    for(int curPos=input.length()-1;curPos>=0;curPos--)
    {
        if(curPos==input.length()-1)
        {
            head=new LLNode<Integer>();
            head.data=input.charAt(curPos)+'0';
            curNode=head;
        }
        else
        {
            curNode.link=new LLNode<Integer>();
            curNode=curNode.link;
            curNode.data=input.charAt(curPos)+'0';
        }
    }
}

1 个答案:

答案 0 :(得分:0)

欢迎堆栈溢出。

如何使用List接口和String类的方法,而不是仅仅用于循环?检查此示例:

String phrase = "this is the phrase"; // this is the input
List<String> list = new LinkedList<>();

// iterates the input in decreasing index order
for(int i=phrase.length()-1; i >= 0; i--) { 
    // gets the character from the input and add to the LinkedList
    list.add(Character.toString(phrase.charAt(i))); 
}

如果不想添加空格,请在添加字符之前添加if(isEmpty(phrase.charAt(i))) continue;

实时示例here

相关问题