Here is simple code to implement Stack without using array.
This is code how you will use it.
This is Application.java
This is Output
This is Stack.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | package com.trickyjava; public class Stack<T> { private StackElement<T> top; public T pop() throws Exception { if (null == top) { throw new Exception("No element in stack"); } T element = top.getElement(); top = top.getPrevious(); return element; } public void push(T element) { if (null == top) { top = new StackElement<T>(null, element); return; } top = new StackElement<T>(top, element); } public void empty() { top = null; } public boolean hasMoreElements() { return null != top; } private class StackElement<T> { private StackElement<T> previous; private T element; public StackElement(StackElement<T> previous, T element) { this.previous = previous; this.element = element; } public T getElement() { return element; } public StackElement<T> getPrevious() { return previous; } } } |
This is code how you will use it.
This is Application.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.trickyjava; public class Application { public static void main(String[] args) { Stack<String> stack = new Stack<>(); stack.push("This"); stack.push("is"); stack.push("stack"); stack.push("implementation"); stack.push("without"); stack.push("using"); stack.push("array"); while (stack.hasMoreElements()) { try { System.out.println(stack.pop()); } catch (Exception e) { e.printStackTrace(); } } } } |
This is Output
array using without implementation stack is This
No comments:
Post a Comment