Mahmoud_Hawara

Copy one Stack to another one

Nov 15th, 2022
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. public class Solver
  2. {
  3.     public static void main(String args[])
  4.     {
  5.         Stack S = new Stack();
  6.        
  7.         S.push(0);
  8.         S.push(5);
  9.    
  10.         Stack T = copyStack(S);
  11.        
  12.         T.display();
  13.         S.display();
  14.     }
  15.  
  16.     public static Stack copyStack(Stack S)
  17.     {
  18.         Stack st = new Stack(), T = new Stack();
  19.         while (S.isEmpty() == false)
  20.         {
  21.             st.push(S.pop().data);
  22.         }
  23.         while (st.isEmpty() == false)
  24.         {
  25.             int temp = st.pop().data;
  26.             T.push(temp);
  27.             S.push(temp);
  28.         }
  29.         return T;
  30.     }
  31.  
  32. }
  33.  
  34. class Node
  35. {
  36.     int data;
  37.     Node next;
  38.  
  39.     public Node(int d)
  40.     {
  41.         data = d;
  42.     }
  43. }
  44.  
  45. class Stack    
  46. {
  47.     Node Top;
  48.  
  49.     public void push(int d)
  50.     {
  51.         Node temp = new Node(d);
  52.         temp.next = Top;
  53.         Top = temp;
  54.         return;
  55.     }
  56.  
  57.     public Node pop()
  58.     {
  59.         if (isEmpty())
  60.         {
  61.             System.out.println("Can't pop, The Stack is Empty");
  62.             return null;
  63.         }
  64.         Node temp = Top;
  65.         Top = Top.next;
  66.         return temp;
  67.     }
  68.  
  69.     public Node top()
  70.     {
  71.         if (isEmpty())
  72.         {
  73.             System.out.println("The Stack is Empty");
  74.         }
  75.         return Top;
  76.     }
  77.  
  78.     public void display()
  79.     {
  80.         if (isEmpty())
  81.         {
  82.             System.out.print("The Stack is Empty");
  83.         }
  84.         Node curr = Top;
  85.         while (curr != null)
  86.         {
  87.             System.out.print(curr.data + " ");
  88.             curr = curr.next;
  89.         }
  90.         System.out.println();
  91.         return;
  92.     }
  93.  
  94.     public boolean isEmpty()
  95.     {
  96.         return Top == null;
  97.     }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment