Stack Implementation
The following Stack class in Java consists of following methods:
- push(int value): Inserts a data item at the top of the stack.
- pop(): Removes the top most data item from the stack.
- peek(): Returns the topmost element of the stack.
- isEmpty(): Returns true if the stack is empty.
- isFull(): Returns true is the stack is full.
The data members of Stack class consists:
- top: Private member to track the topmost element of the stack.
- size: Private member to track the maximum capacity of the stack.
- arr[]: Private array to implement the stack.
Static Implementation
class Stack {
private int top;
private int size;
private int arr[];
Stack(int size) {
top = -1;
this.size = size;
arr = new int[this.size];
}
boolean push(int value) {
if (top == size - 1)
return false;
top++;
arr[top] = value;
return true;
}
boolean pop() {
if (top == -1)
return false;
top--;
return true;
}
int peek() {
if (top == -1)
return -1;
return arr[top];
}
boolean isEmpty() {
if (top == -1)
return true;
return false;
}
boolean isFull() {
if (top == size - 1)
return true;
return false;
}
}
Dynamic Implementation
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
class Stack {
private Node top;
Stack() {
top = null;
}
boolean push(int value) {
Node node = new Node(value);
if (top != null)
node.next = top;
top = node;
return true;
}
boolean pop() {
if (top == null)
return false;
Node temp = top;
top = temp.next;
temp.next = null;
return true;
}
int peek() {
if (top == null)
return -1;
return top.data;
}
boolean isEmpty() {
if (top == null)
return true;
return false;
}
}
Comments
Post a Comment