Writing a Stack using Array
package com.saroj.stack;
/**
* @author saroj
*
*/
public class MyStack {
public static void main(String[] args) {
Stack myStack = new Stack(10);
for(int i=0; i<10; i++){
myStack.push(i);
}
for(int i=0; i<5; i++){
System.out.println(myStack.pop());
}
}
static class Stack{
int size;
int top;
int[] array;
public Stack(int maxSize){
this.size=maxSize;
top = -1;
array = new int[maxSize];
}
public void push(int val){
array[++top] = val;
}
public int pop(){
int result = array[top];
top--;
return result;
}
public int peek(){
return array[top];
}
}
}
Writing a Dynamic Stack using resized Array
package com.saroj.stack;
/**
* @author saroj
*
*/
public class MyDynamicStack {
public static void main(String[] args) {
DynamicStack myStack = new DynamicStack(10);
for(int i=0; i<10; i++){
myStack.push(i);
}
for(int i=0; i<5; i++){
System.out.println(myStack.pop());
}
}
static class DynamicStack{
int size;
int[] stackArr;
int top;
public DynamicStack(int maxSize){
top = -1;
this.size=maxSize;
stackArr = new int[maxSize];
}
public void push(int val){
if(isFull()){
increaseCapacity();
}else{
stackArr[++top] = val;
}
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("Stack is empty");
}
int item = this.stackArr[top--];
return item;
}
// To check if the stack is full
public boolean isFull(){
return (top == stackArr.length-1);
}
//check if the stack is empty
public boolean isEmpty(){
return (top == -1);
}
//increase the capacity fo stack
public void increaseCapacity(){
int[] newArray = new int[this.size*2];
for(int i=0; i<size;i++){
newArray[i] = stackArr[i];
}
this.stackArr = newArray;
this.size=size*2;
}
}
}
How to sort a Stack without using any data structure like array etc.?
package com.saroj.stack;
import java.util.Stack;
public class SortingAStack {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(10);
stack.push(5);
stack.push(3);
stack.push(12);
stack.push(6);
stack.push(7);
stack.push(1);
stack.push(14);
System.out.println(SortingAStack.sort(stack));
}
public static Stack sort(Stack stack1){
Stack stack2 = new Stack();
while(!stack1.isEmpty()){
int temp = stack1.pop();
while(!stack2.isEmpty() && stack2.peek() > temp){
stack1.push(stack2.pop());
}
stack2.push(temp);
}
return stack2;
}
}
