Mahmoud_Hawara

Using Stack to reverse each Word in a sentence Separately

Nov 15th, 2022
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. public class Solver
  2. {
  3.     public static void main(String args[])
  4.     {
  5.         System.out.println(reverse("DR Sahar 3yota"));
  6.     }
  7.  
  8.     public static StringBuilder reverse(String inp)
  9.     {
  10.         StringBuilder ret = new StringBuilder("");
  11.         Stack st = new Stack();
  12.        
  13.         for (int i = 0; i < inp.length(); i++)
  14.         {
  15.             char c = inp.charAt(i);
  16.             if (c != ' ')st.push(c);
  17.             else
  18.             {
  19.                 while (st.isEmpty() == false)
  20.                 {
  21.                     ret.append(st.pop().ch);
  22.                 }
  23.                 ret.append(' ');
  24.             }
  25.         }  
  26.         while (st.isEmpty() == false)
  27.         {
  28.             ret.append(st.pop().ch);
  29.         }
  30.        
  31.         return ret;
  32.     }
  33. }
  34.  
  35. class Node
  36. {
  37.     char ch;
  38.     Node next;
  39.  
  40.     public Node(char c)
  41.     {
  42.         ch = c;
  43.     }
  44. }
  45.  
  46. class Stack    
  47. {
  48.     Node Top;
  49.  
  50.     public void push(char c)
  51.     {
  52.         Node temp = new Node(c);
  53.         temp.next = Top;
  54.         Top = temp;
  55.         return;
  56.     }
  57.  
  58.     public Node pop()
  59.     {
  60.         if (isEmpty())
  61.         {
  62.             System.out.println("Can't pop, The Stack is Empty");
  63.             return null;
  64.         }
  65.         Node temp = Top;
  66.         Top = Top.next;
  67.         return temp;
  68.     }
  69.  
  70.     public Node top()
  71.     {
  72.         if (isEmpty())
  73.         {
  74.             System.out.println("The Stack is Empty");
  75.         }
  76.         return Top;
  77.     }
  78.  
  79.     public boolean isEmpty()
  80.     {
  81.         return Top == null;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment