Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DynamicStack {
- private class Node {
- Object element;
- Node next;
- public Node(Object element, Node next) {
- this.element = element;
- next.next = this;
- }
- Node(Object element) {
- this.element = element;
- this.next = null;
- }
- }
- public Node head;
- public Node tail;
- public int count;
- public DynamicStack() {
- this.head = null;
- this.tail = null;
- this.count = 0;
- }
- public void push(Object o) {
- if(head == null) {
- head = new Node(o);
- tail = head;
- } else {
- Node node = new Node(o, tail);
- tail = node;
- }
- count++;
- }
- public Object pop() {
- Object popedElement = tail.element;
- count--;
- if(count == 0) {
- tail = null;
- head = null;
- } else {
- int counter = 0;
- DynamicStack.Node iterator = head;
- while (counter != count) {
- tail = iterator;
- iterator = iterator.next;
- counter++;
- }
- }
- return popedElement;
- }
- public Object peek() {
- return this.tail.element;
- }
- public int size() {
- return this.count;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement