Advertisement
vov44k

t58

Nov 20th, 2022
567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Stacki {
  5.     public static void main(String[] args) throws IOException {
  6.         Stack stack = new Stack(5000);
  7.         BufferedReader in = new BufferedReader(new InputStreamReader (new FileInputStream(new File("input.txt"))));
  8.         StreamTokenizer input = new StreamTokenizer(in);
  9.         PrintWriter out = new PrintWriter(new File("output.txt"));
  10.         while (true) {
  11.  
  12.             input.nextToken();
  13.             String a = input.sval;
  14.             if (a.equals("push")) {
  15.  
  16.                 input.nextToken();
  17.                 stack.push((int) input.nval);
  18.                 out.println("ok");
  19.             }
  20.             if (a.equals("front")) {
  21.                 if (stack.size()==0){
  22.                     out.println("error");
  23.                 } else {
  24.                     out.println(stack.top()) ;
  25.                 }
  26.             }
  27.             if (a.equals("size")) {
  28.                 out.println(stack.size()) ;
  29.             }
  30.             if (a.equals("clear")) {
  31.                 stack.clear() ;
  32.                 out.println("ok") ;
  33.             }
  34.             if (a.equals("exit")) {
  35.                 out.println("bye") ;
  36.                 out.close();
  37.                 return;
  38.             }
  39.             if (a.equals("pop")) {
  40.                 if (stack.size()==0){
  41.                     out.println("error");
  42.                 } else {
  43.                     out.println(stack.pop()) ;
  44.                 }
  45.             }
  46.         }
  47.     }
  48. }
  49.  
  50. class Stack {
  51.     int[] stack;
  52.     int head = 0;
  53.     int tail = 0;
  54.     public Stack(int length){
  55.         stack = new int[length];
  56.     }
  57.     void clear() {
  58.         head = tail;
  59.     }
  60.     int size() {
  61.         return tail-head;
  62.     }
  63.     int top() {
  64.         return stack[head%stack.length] ;
  65.     }
  66.     int pop(){
  67.         head++;
  68.         return stack[(head-1)%stack.length];
  69.     }
  70.     void push(int n) {
  71.         stack[tail%stack.length] = n;
  72.         tail++;
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement