有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java反转字符的字符串顺序,并使用构造函数将其放入LinkedList

我正在制作一个程序,它接受一个字符串,并将其以相反的顺序放入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) 个答案

  1. # 1 楼答案

    欢迎来到Stack Overflow

    如何使用列表接口和字符串类的方法,而不仅仅是循环?检查以下示例:

    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