Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.chamika;
- import java.util.Iterator;
- /**
- * Created by dinu on 12/13/17.
- */
- public class Stack {
- public static void main(String[] args) {
- StackDataStructure<Integer> stackDataStructure = new StackDataStructure();
- stackDataStructure.print();
- stackDataStructure.push(9);
- stackDataStructure.push(7);
- stackDataStructure.push(89);
- stackDataStructure.print();
- stackDataStructure.pop();
- stackDataStructure.print();
- stackDataStructure.pop();
- stackDataStructure.print();
- stackDataStructure.pop();
- stackDataStructure.print();
- StackDataStructure<String> stringstack = new StackDataStructure<>();
- stringstack.push("Amma");
- stringstack.push("Thaththa");
- stringstack.push("Baba");
- stringstack.print();
- System.out.println("Testing Iterable");
- for (StackNode node : stringstack) {
- System.out.println(node.value);
- }
- // StackNode<String> s1 = new StackNode<>();
- // s1.value = "A";
- // StackNode<String> s2 = new StackNode<>();
- // s2.value = "B";
- // StackNode<String> s3 = new StackNode<>();
- // s3.value = "C";
- // s1.next = s2;
- // s2.next = s3;
- // for(String s:s1){
- //
- // }
- }
- }
- class StackDataStructure<T> implements Iterable<StackNode> {
- StackNode<T> tail;
- StackNode<T> head;
- void push(T value) {
- if (head == null) {
- head = new StackNode();
- head.value = value;
- head.next = null;
- tail = head;
- tail.previous = null;
- } else {
- tail.next = new StackNode();
- tail.next.value = value;
- tail.next.previous = tail;
- tail.next.next = null;
- tail = tail.next;
- }
- }
- StackNode pop() {
- if (head == null) {
- return null;
- } else {
- StackNode node = tail;
- if (tail.previous == null) {
- head = null;
- tail = null;
- return node;
- }
- tail = tail.previous;
- tail.next = null;
- return node;
- }
- }
- void print() {
- System.out.println("Printing Stack");
- if (head == null) {
- System.out.println("Stack is Empty");
- } else {
- StackNode node = head;
- while (node != null) {
- System.out.print(node.value + " ");
- node = node.next;
- }
- }
- System.out.println("\nPrinting Stack Finished");
- }
- @Override
- public Iterator<StackNode> iterator() {
- return new StackNodeIterator(head);
- }
- }
- class StackNode<T> {
- T value;
- StackNode next;
- StackNode previous;
- public StackNode getNext() {
- return next;
- }
- }
- class StackNodeIterator implements Iterator<StackNode> {
- StackNode next;
- public StackNodeIterator(StackNode next) {
- this.next = next;
- }
- @Override
- public boolean hasNext() {
- return (next != null);
- }
- @Override
- public StackNode next() {
- StackNode ret = next;
- next = next.next;
- return ret;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement