Reverse String order of characters and place into LinkedList using a constructor

安稳与你 提交于 2019-12-13 23:26:27

问题


I am making a program that takes a String and puts it in the opposite order into a LinkedList.

This code doesn't seem to work (wrong input), and I can't figure out why. Any solutions?

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:


Welcome to Stack Overflow.

What about to use the methods of List interface and String class, instead of just for loops? Check this example:

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 you want not to add white spaces, add if(isEmpty(phrase.charAt(i))) continue; before adding the character.

Live example here.



来源:https://stackoverflow.com/questions/55033986/reverse-string-order-of-characters-and-place-into-linkedlist-using-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!