Reputation: 191
I am new to data structures and programming in general, and im learning the concept of a stack by implementing a string reverser. As i wanted to use the stack size as a counter to pop all the items in the stack, i notice that the stack size does not return the number of items in the stack. Example:
public String reverse(String string) {
StringBuffer stringBuffer = new StringBuffer();
//Use a stack to reverse this string.As a stack is a LIFO collection, it goes by last in first out.
Stack<Character> characters = new Stack<>();
char[] characterArray = string.toCharArray();
for(char ch : characterArray) {
characters.push(ch);
}
for(int i=0; i < characterArray.length; i++) {
stringBuffer.append(characters.pop());
}
return stringBuffer.toString();
}
input " helloworldz" returns "zdlrowolleh" as expected. But when using the stack size as a counter....
public String reverse(String string) {
StringBuffer stringBuffer = new StringBuffer();
Stack<Character> characters = new Stack<>();
char[] characterArray = string.toCharArray();
for(char ch : characterArray) {
characters.push(ch);
}
for(int i=0; i < characters.size(); i++) {
stringBuffer.append(characters.pop());
}
return stringBuffer.toString();
}
it returns "zdlrow",
meaning that the stack size did not return the number of items in the stack. Am i missing anything important? any help would be appreciated.
Upvotes: 0
Views: 163
Reputation: 9
Java provides the Iterator interface for iterate through complex data structures like stack, map and lists. you might have to refactor your code to use the iterator interface.
Iterator<Character> iterator = stack.iterator();
while(iterator.hasNext()){
sb.append(stack.pop());
}
Upvotes: 1
Reputation: 4592
If you wanted to do a loop conditioned on information from the characters
stack itself, the proper choice would be:
while (!characters.isEmpty()) {
stringBuffer.append(characters.pop());
}
Upvotes: 1
Reputation: 79035
The size of the stack is decreased by 1
with every pop
operation on it and therefore in the following code block,
for(int i=0; i < characters.size(); i++) {
stringBuffer.append(characters.pop());
}
the loop will be executed for only the half number of times as compared to that in the following code block
for(int i=0; i < characterArray.length; i++) {
stringBuffer.append(characters.pop());
}
Upvotes: 2