Stack Implementation
import java.util.Arrays;
public class Stack {
private int count=0;
private T[] data;
Stack(){
data = (T[]) new Object[1];
}
public int size() {
return count;
}
public boolean isEmpty() {
return count==0;
}
public void push(T newItem) {
if(count==data.length) {
resize(2*data.length);
}
data[count++] = newItem;
}
public T pop() {
T item = data[--count];
if(count>0 && count == (data.length/4)){
resize(data.length/2);
}
return item;
}
public void resize(int newCapacity){
T stackCopy[] = Arrays.copyOf(data, newCapacity);
data = stackCopy;
}
}
App Runner:-
public class StackApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack stack = new Stack();
stack.push(10);
stack.push(30);
stack.push(4);
stack.push(7);
stack.push(14);
while(!stack.isEmpty())
System.out.println(stack.pop());
}
}
Output:-
14
7
4
30
10
Thursday, February 4, 2021
Stack Implementation using Array Data structure
Subscribe to:
Post Comments (Atom)
How to find middle node of LinkedList without using extra memory in java
To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...
-
public class ReverseArrayWithoutExtraMemory { public static void main(String[] args) { int arr[] = {1,2,3,4,5,6}; int swapArray[] =...
-
1) List Interface Implementation public interface List<T extends Comparable<T>> { public Node<T> getMi...
-
function data_change(field) { var check = true; var value = field.value; //get characters //check that all ch...
No comments:
Post a Comment