Wed Oct 24, 2012 10:45 pm
import java.awt.Color;
public class StackExample {
public static void main(String[] args) {
Color c1 = new Color(54, 43, 75);
Color c2 = new Color(4, 100, 175);
Color c3 = new Color(100, 53, 160);
JavaStack stack = new JavaStack(2);
stack.push(c1);
stack.push(c2);
stack.push(c3);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());// Empty
stack.push(c3);
stack.push(c2);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());// Empty
System.out.println(stack.pop());// Empty
}
}
public class JavaStack {
private int top;
// Array to store objects
private Object[] stackBox;
JavaStack(int capacity) {
stackBox = new Object[capacity];
top = -1;
}
void push(Object value) {
if (top+1 == stackBox.length) {
System.out.println("For Value: " + value + ","
+ " We can't add more values to the "
+ " (Stack is full)");
} else {
top++;
stackBox[top] = value;
}
}
Object peek() {
if (top == -1) {
System.out.println("Stack is empty");
return null;
} else {
return stackBox[top];
}
}
Object pop() {
if (top == -1) {
System.out.println("Stack is empty");
return null;
} else {
// Decreases the value after assigning it stackBox
return stackBox[top--];
}
}
boolean isEmpty() {
// True if empty
return (top == -1);
}
}
For Value: java.awt.Color[r=100,g=53,b=160], We can't add more values to the (Stack is full)
java.awt.Color[r=4,g=100,b=175]
java.awt.Color[r=54,g=43,b=75]
Stack is empty
null
java.awt.Color[r=4,g=100,b=175]
java.awt.Color[r=100,g=53,b=160]
Stack is empty
null
Stack is empty
null
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.