Monday, November 4, 2019

Data Structure Interview Question - Stack

1.  Implement a stack using array.

Stack is abstract data type which demonstrates Last in first out (LIFO) behavior. We will implement same behavior using Array.
Although java provides implementation for all abstract data types such as Stack,Queue and LinkedList but it is always good idea to understand basic data structures and implement them yourself.
Please note that Array implementation of Stack is not dynamic in nature. You can implement Stack through linked list for dynamic behavior.

package com.sid.datastructure.stack;

public class ImplementStackUsingArray {

int arr[];
int top = -1;
int size;

public ImplementStackUsingArray(int size) {
this.arr = new int[size];
this.top = -1;
this.size = size;
}

// push
// popo
// peek

private void push(int pushedElement) {
if (!isFull()) {
arr[++top] = pushedElement;
System.out.println("Element pushed " + pushedElement);
} else {
System.out.println("Stack is full");
}

}

private int pop() {
if (!isEmpty()) {
System.out.println(arr[top]);
return arr[top--];
} else {
System.out.println("Stack is empty");
return -1;
}

}

private int peek() {
if (!isEmpty()) {
return arr[top];
} else {
System.out.println("Stack is empty. Cannot peek");
return -1;
}

}

private boolean isEmpty() {
return top == -1;
}

private boolean isFull() {
return (top == size - 1);
}

public static void main(String[] args) {
ImplementStackUsingArray stack = new ImplementStackUsingArray(10);
stack.pop();
System.out.println("=================");
stack.push(10);
stack.push(30);
stack.push(50);
stack.push(40);
System.out.println("=================");
stack.pop();
stack.pop();
stack.pop();
System.out.println("=================");
}

}

2. Implement a stack using two queues .

For more questions , visit the following link :

https://java2blog.com/data-structure-and-algorithm-interview-questions-in-java/

No comments:

Post a Comment