Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class StackNode<E> {
- private E data;
- private StackNode<E> next;
- public StackNode(E data){
- this.data = data;
- this.next = null;
- }
- public StackNode<E> getNext(){
- return this.next;
- }
- public void setNext(StackNode<E> next){
- this.next = next;
- }
- public E getData(){
- return this.data;
- }
- }
- import java.util.NoSuchElementException;
- public class Stack<E> {
- private StackNode<E> top;
- private int size;
- public Stack(E data){
- StackNode<E> node = new StackNode<E>(data);
- this.top = node;
- }
- public Stack(){
- this.top = null;
- }
- public StackNode<E> peek(){
- return this.top;
- }
- public int getSize(){
- return this.size;
- }
- public void increaseSize(){
- this.size++;
- }
- public void decreaseSize(){
- this.size--;
- }
- public StackNode<E> pop(){
- StackNode<E> node = this.top;
- this.top = this.top.getNext();
- decreaseSize();
- return node;
- }
- public void push(E data){
- StackNode<E> node = new StackNode<E>(data);
- node.setNext(this.top);
- increaseSize();
- this.top = node;
- }
- public void print(){
- StackNode<E> node = this.top;
- if (node==null){
- throw new NoSuchElementException();
- }
- StringBuilder s = new StringBuilder();
- while (node!=null){
- s.append(node.getData()+" ");
- node=node.getNext();
- }
- System.out.println(s);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment