Skip to content

Instantly share code, notes, and snippets.

@yaswanthrajyadiki
Last active September 21, 2015 04:57
Show Gist options
  • Save yaswanthrajyadiki/1647d5e5536f8d7a8c7a to your computer and use it in GitHub Desktop.
Save yaswanthrajyadiki/1647d5e5536f8d7a8c7a to your computer and use it in GitHub Desktop.
class LinkedListStack<T> {
Node<T> bottom;
Node<T> top;
MyStack() {
bottom = new Node<T>();
top = new Node<T>();
}
public void push(T element) {
Node<T> newNode = new Node<T>();
newNode.setElement(element);
if (bottom == null) {
bottom = newNode;
top = newNode;
} else {
newNode.setNextElement(top);
top = newNode;
}
}
public void pop() {
Node<T> nextNode = top.getNextElement();
top = nextNode;
}
public T getTop() {
if (isEmpty()) {
return null;
}
return top.getElement();
}
public boolean isEmpty() {
if (top == null) {
return true;
}
return false;
}
public void print() {
Node<T> printNode = top;
if (!isEmpty()) {
while (printNode.getElement() != null){
System.out.println(printNode.getElement());
printNode = printNode.getNextElement();
}
} else {
System.out.println("Stack is empty");
}
}
public static void main(String[] args) {
LinkedListStack<Integer> myStack1 = new LinkedListStack<Integer>();
myStack1.push(1);
myStack1.push(2);
myStack1.push(3);
myStack1.push(4);
myStack1.push(5);
myStack1.push(6);
myStack1.pop();
System.out.println(myStack1.getTop());
myStack1.print();
}
}
class Node<T> {
T element;
Node<T> nextElement;
public void setElement(T element) {
this.element = element;
}
public T getElement() {
return this.element;
}
public void setNextElement(Node<T> nextElement) {
this.nextElement = nextElement;
}
public Node<T> getNextElement() {
return this.nextElement;
}
}
@SuppressWarnings("unchecked")
class MyStack<T> implements StackADT<T> {
T[] stack;
int top;
int size;
MyStack (int size) {
this.size = size;
stack = (T[]) new Object[size];
top = -1;
}
public void push(T element) {
if (top < size - 1) {
top++;
stack[top] = element;
} else {
System.out.println("Overflow");
}
}
public void pop() {
if (!isEmpty()) {
top--;
} else {
System.out.println("Underflow");
}
}
public T getTop() {
return stack[top];
}
public boolean isEmpty() {
if (top == -1) {
return true;
}
return false;
}
public void print() {
if (!isEmpty()) {
for (int i = 0; i < top + 1; i++) {
System.out.println(stack[i]);
}
} else {
System.out.println("Underflow");
}
}
public static void main(String[] args) {
MyStack<Integer> newStack = new MyStack<Integer>(5);
newStack.push(1);
newStack.push(2);
newStack.push(3);
newStack.push(4);
newStack.push(5);
newStack.push(6);
newStack.pop();
System.out.println(newStack.getTop());
System.out.println(newStack.isEmpty());
newStack.print();
}
}
interface StackADT<T> {
void push(T element);
void pop();
T getTop();
boolean isEmpty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment