问题
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