ADVERTISEMENT

Java Program to show Stack Implementation

ADVERTISEMENT

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.

/*******************************************************
* 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

 

ADVERTISEMENT
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post