Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Stack {
- private Node top;
- private final int maxSize;
- private int size;
- static class Node {
- Object data;
- Node next;
- }
- public Stack(int maxSize) {
- this.top = null;
- this.maxSize = maxSize;
- this.size = 0;
- }
- public void push(Object data) {
- if (size == maxSize) {
- throw new RuntimeException("Stack is full");
- }
- Node node = new Node();
- node.data = data;
- node.next = top;
- top = node;
- size++;
- }
- public Object pop() {
- if (size == 0) {
- throw new RuntimeException("Stack is empty");
- }
- Object data = top.data;
- top = top.next;
- size--;
- return data;
- }
- public Object peek() {
- if (size == 0) {
- throw new RuntimeException("Stack is empty");
- }
- return top.data;
- }
- public int size() {
- return size;
- }
- public boolean isEmpty() {
- return size == 0;
- }
- public boolean isFull() {
- return size == maxSize;
- }
- public void clear() {
- top = null;
- size = 0;
- }
- public void print() {
- Node node = top;
- while (node != null) {
- System.out.println(node.data);
- node = node.next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement