Thursday, 15 November 2018

how to implement stack using dynamic array


public class StackWithArray {

private int capacity = 2;
private int stack[] = new int[capacity];
private int top = 0;

public void push(int data) {

if (size() == capacity)
expand();

stack[top] = data;
top++;

}

private void expand() {
int length = size();

int[] newStack = new int[capacity * 2];
System.arraycopy(stack, 0, newStack, 0, length);
stack = newStack;
capacity *= 2;

}

private int size() {
return top;
}

public int pop() {
int data = 0;
if (isEmpty()) {
System.out.println("stack is empty");
} else {
top--;
data = stack[top];
stack[top] = 0;
shrink();

}
return data;
}

public int peek() {
int data;
data = stack[top - 1];
return data;

}

private void shrink() {
int length = size();
if (length <= (capacity / 2) / 2)
capacity = capacity / 2;

int newStack[] = new int[capacity];
System.arraycopy(stack, 0, newStack, 0, length);
stack = newStack;
}

public boolean isEmpty() {
return top <= 0;
}

public void displayData() {
for (int n : stack) {
System.out.print(n + " ");
}
System.out.println();

}

public static void main(String[] args) {

StackWithArray st = new StackWithArray();
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
st.pop();
st.displayData();
st.pop();
st.displayData();
st.pop();
st.displayData();
st.pop();
st.displayData();

}

}

Wednesday, 14 November 2018

How To implement Stack in Java


public class MyStack {

int data[]=new int[5];

int top=0;
static int size=0;

public void push(int value) {
data [top]=value;
top++;
size++;
}

int pop() {
int d=0;
for(int i=size-1; i>=0; i--) {
System.out.println(data[i]);
d=data[i];
data[i]=0;
}

return d;
}

public static void main(String[] args) {

MyStack st=new MyStack();
st.push(1);
st.push(5);
st.push(2);
st.push(0);
st.push(1);
st.pop();
}

}

How to implement custom Queue in Java

public class MyQueue {
public static void main(String[] args) {


Queue q = new Queue();
q.enQueue(5);
q.enQueue(8);
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
q.show();
}
}

class Queue {
int size;
int[] queue;

int front;
int rear;

Queue() {
size = 0;
queue = new int[5];
}

public void enQueue(int data) {
queue[rear] = data;
rear = rear + 1;
size = size + 1;
}

public void show() {
for (int i = 0; i < queue.length; i++) {
System.out.println(queue[i]);
}
}

}