Sunday 7 June 2015

Linked list based Stack in java with feature of 'for each' loop.

Hello friends,
Below is a code which shows how we can implement Linked list based stack using Java.
It also shows how we can implement Iterator and can enable usage of  'for each' in our custom class.
import java.util.EmptyStackException;
import java.util.Iterator;

public class LinkedListStack implements Iterable {
    public static class Node {
        Node next;
        int data;

        public Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    private Node top = null;
    int size = 0;

    public void push(int data) {
        Node newNode = new Node(data, null);
        if (top != null) {
            newNode.next = top;
        }
        top = newNode;
        size++;
    }

    public int pop() {
        int data;
        if (top != null) {
            data = top.data;
            top = top.next;
            size--;
        } else {
            throw new EmptyStackException();
        }
        return data;
    }

    private class StackIterator implements Iterator {
        int index = size;
        Node iteratorTop = LinkedListStack.this.top;

        @Override
        public boolean hasNext() {
            return index > 0;
        }

        @Override
        public Integer next() {
            int i = iteratorTop.data;
            iteratorTop = iteratorTop.next;
            index--;
            return i;
        }

        @Override
        public void remove() {
            pop();
            index--;
        }
    }

    @Override
    public Iterator iterator() {
        return new StackIterator();
    }
}





Now lets test our Stack.

public class StackTest {
 public static void main(String[] args) {
  LinkedListStack stack = new LinkedListStack();
  stack.push(0);
  stack.push(1);
  stack.push(2);
  stack.push(1);
  stack.push(3);
  stack.push(4);
  System.out.println(stack.pop());
  System.out.println(stack.pop());
  for(int i : stack){
   System.out.println(i);
  }
 }
}

Result is 
4
3
1
2
1
0


Happy coding :)

No comments:

Post a Comment

Hi Friends, Please leave your comments as they shall be greatest motivation , shall help me make corrections to my existing posts and will enable me to create better posts. :)