Stack Implementation Java Code


 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package LinearDS;

public class ImplementStack {

 public static void main(String[] args) {
  Stack obj = new Stack(4);
  obj.push("1");
  System.out.println(obj.peek());
  obj.push("2");
  System.out.println(obj.peek());
  obj.push("3");
  System.out.println(obj.peek());
  obj.push("4");
  System.out.println(obj.peek());
  obj.push("5");

  //System.out.println(obj.peek());
 }

}

class Stack {
 int maxsize;
 int top;
 String[] arr;

////////////////////////////////////////constructor
 public  Stack(int n) {
  maxsize = n;
  arr = new String[maxsize];
  top = 0;
 }

 ////////////////////////////////////EMPTY
 public boolean empty() {
  if (top == 0) {
   return true;
  } else
   return false;
 }


 ///////////////////////////////////PUSH
 public void push(String str) {
  if (top < maxsize) {
   arr[top] = str;
   top++;
  }
  else {
   System.out.println("stack overflow");
  }

 }

 //////////////////////////////////// POP
 public String pop() {
  if ( !this.empty()) {
   String temp = this.peek();
   arr[top - 1] = null;
   top--;
   return temp;
  } else {
   return null;
  }
 }


 //////////////////////////////////////PEEK
 public String peek() 
  if (top > 0) {
   return arr[top - 1];
  } else {
   return null;
  }
 }

}

No comments:

Post a Comment