Learn-dsa..in 30 days!



























CC-2 : Implement Stack using array.

Description:

Create and test a Stack using array for storage instead of LinkedList.

Test cases and expected outputs:

Input Parameters Expected outputs
Stack stack=new Stack();
stack.add(9);
stack.add(14);
stack.add(17);
stack.add(34);
stack.add(21);
stack.add(28);
Queue nodes: 28 <- 21 <- 34 <- 17 <- 14 <- 9
stack.remove();
stack.remove();
stack.remove();
Queue nodes: 17 <- 14 <- 9

Pseudocode:

The Array Stack should instantiate and use a fixed size array for storing data elements. The last index of array at which a data element is present also needs to be tracked.
The add() method: If array storage is not full, this method moves all existing elements right by one index and then adds the new element to 0 index of the array. Once the array is full, the add() method does not add the element to the array and returns false.
The remove() method: if storage array is empty, return false, else return the first element of the array and shift all data elements in the array left by 1 index.

Code:

public class StackArray {
	
private int[] stack=new int[10];	
private int lastIdx=-1;
	
public int get() {
	if (lastIdx != -1) {
		return stack[lastIdx];
	}
	return Integer.MIN_VALUE;
}

public boolean add(int data){
	if (lastIdx == stack.length-1) {return false;}
	lastIdx++;
	stack[lastIdx]=data;
	return true;
}

public int remove() {
	if (lastIdx == -1) {return Integer.MIN_VALUE;}
	int removedData=stack[lastIdx];
	stack[lastIdx]=0;
	lastIdx--;
	return removedData;
}
}

Click here to download and run code and test cases !