-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseWords.java
35 lines (30 loc) · 933 Bytes
/
ReverseWords.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package Stack;
public class ReverseWords {
static void reverseWords(String str)
{
Stack<Character> st = new Stack<Character>();
// Traverse given string and push all
// characters to stack until we see a space.
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) != ' ')
st.push(str.charAt(i));
// When we see a space, we print
// contents of stack.
else {
while (st.empty() == false) {
System.out.print(st.pop());
}
System.out.print(" ");
}
}
// Since there may not be space after
// last word.
while (st.empty() == false) {
System.out.print(st.pop());
}
}
public static void main(String[] args) {
String str = "Geeks for Geeks";
reverseWords(str);
}
}