简体   繁体   中英

Use linked list or array to reverse a string in Java?

I believe that we can use a for loop to reverse a string in Java. Just like below:

String[] name = new String[10];

for(int i = name.length; i >0; i--){

    System.out.print(name[i-1]);

}

But another implementation is using LinkedList. So my understanding is to use LinkedList when the client is not sure how long the string array might increase dynamically. Is that correct?

A linked list of characters can be used to do this.

In this instance, think of an array list as an array with unlimited length. For this, instead of adding values to the END of the array, we will add them to the BEGINNING of the linked list

LinkedList<Character> linkedList = new LinkedList<Character>();
String str = "Hello World";

for (int i = 0; i < str.length(); i++) {
    linkedList.addFirst(str.charAt(i));
}

//whenever it is time to print the value....
for (char c : linkedList) {
    //Print it out, one character at a time
    System.out.print(c);
}

Whenever you have to add more characters to it, just use linkedList.addFirst() to append it to the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM