This is a simple Java program to demonstrate Stack data structure implementation. An object of type IntStack is a stack of real numbers, with the standard stack operations push(int N), pop(), and isEmpty(). A makeEmpty() operation is also provided to remove all items from the stack.
Internally, the stack is implemented as a linked list.
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 | /******************************************************* * MYCPLUS Sample Code - https://www.mycplus.com * * * * This code is made available as a service to our * * visitors and is provided strictly for the * * purpose of illustration. * * * * Please direct all inquiries to saqib at mycplus.com * *******************************************************/ public class NumberStack { private static class Node { // An object of type Node holds one of the // items on the stack; double item; Node next; } private Node top; // Pointer to the Node that is at the top of // of the stack. If top == null, then the // stack is empty. public void push( double N ) { // Add N to the top of the stack. Node newTop = new Node(); newTop.item = N; newTop.next = top; top = newTop; } public double pop() { // Remove the top item from the stack, and return it. // Note that this routine will throw a NullPointerException // if an attempty is made to pop an item from an empty // stack. (It would be better style to define a new // type of Exception to throw in this case.) double topItem = top.item; top = top.next; return topItem; } public boolean isEmpty() { // Returns true if the stack is empty. Returns false // if there are one or more items on the stack. return top == null; } } // end class NumberStack |