Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class App {
- public static void main(String[] args) {
- Stack theStack = new Stack(5);
- ////
- // theStack.push('h'); //0
- // theStack.push('e'); //1
- // theStack.push('l'); //2
- // theStack.push('l'); //3
- // theStack.push('o'); //4
- //
- // while (!theStack.isEmpty()) {
- // char value = theStack.pop();
- // System.out.print(value);
- // }
- String input = "hola como estas hello how are you";
- System.out.println(reverseString(input));
- }
- public static String reverseString(String str){
- int stackSize = str.length(); // get the max stack size
- Stack theStack = new Stack(stackSize); // we make the stack
- for(int j = 0; j < str.length(); j++){
- char ch = str.charAt(j); // getting a char from the input string
- theStack.push(ch);
- }
- String result = "";
- while(!theStack.isEmpty()){
- char ch = theStack.pop();
- result = result+ ch; // appending to the output
- }
- return result;
- }
- }
- public static class Stack {
- private final int maxSize;
- private final char[] stackArray;
- private int top;
- public Stack(int size) {
- this.maxSize = size;
- this.stackArray = new char[maxSize];
- this.top = -1;
- }
- public void push(char j) { // top=0 top=1 top=2 top=3
- if (isFull())
- System.out.println("stack is full");
- else
- top++;
- stackArray[top] = j;
- // stackArray[0]=20; stackArray[1]=40 stackArray[2]=60 stackArray[3]=80
- }
- public char pop() {
- if (isEmpty()) {
- System.out.println("stack is empty");
- return '0';
- } else {
- int old_top = top; //top=3
- top--;
- return stackArray[old_top]; // return 3 80 60 40 20
- } //top=2
- }
- public char peak() {
- return stackArray[top];
- }
- public boolean isEmpty() {
- return (top == -1);
- }
- public boolean isFull() {
- return (maxSize - 1 == top);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement