Stack In JAVA
Submitted by moazkhan on Thursday, August 6, 2015 - 13:11.
Stack in JAVA
In this tutorial you will learn 1) What is a stack? 2) How is stack used in programming? 3) Implementation of stack in JAVA What is a stack? Stack is one of the most important data structure in programming, it can be imagined as the bottle of balls which is open from one end. So the addition and deletion of balls can be done through one end only. The element which goes last in the stack is first to be extracted from the stack. So the stack works on last in first out principle (LIFO). How is stack used in programming Stack is very useful for programming purposes. The stack can be used to store the last used values of some variables as well as in operating system and micro controller programming the stacks can be used handle interrupts and used to store the program counter values and addresses. Implementation of stack in JAVA The stack in JAVA is implemented using ordinary array. Stack has few functions associated with it. They are: Push: Used to put data into the stack Pop: Used to remove data from the top of the stack Top: The first element of the array is called the top of the stack. In the code below first I have defined the class Stack, this class contains data members, methods and the constructor which initialize the data members. Then in the main of the program I have the object of stack class and performed operations on it using its methods. The detail and significance of each line is provided in the comments with the code below.- import java.util.Scanner;
- public class UsingJAVA {
- private int maximumSize; //its the size of the array
- private int[] structure; //this is the array in which the contents are stored
- private int top;
- {
- maximumSize = M; //The size of the array is of the user's choice
- structure = new int[maximumSize]; // we are making an array
- top = -1; // top is declared -1 because we need to access the 0th postion at first insertion
- }
- public void push(int j) //function to put values into stack.
- {
- structure[++top] = j; //the value of top pointer is increased and value is inserted
- }
- public int pop() //to take data out of the stack
- {
- return structure[top--]; //decrement takes the top to the element below the top element
- }
- public boolean isEmpty() //standard function to check whether the stack is empty or not
- {
- return (top == -1);
- }
- public boolean isFull() //standard function to check if the stack is full?
- {
- return (top == maximumSize - 1);
- }
- int x;
- x=inputScanner.nextInt();
- for(int j=0; j<x ;j++) //for loop used to insert the number of values into the stack
- { int z;
- z=inputScanner.nextInt();
- Workstack.push(z); //pushing a value into stack
- }
- while (!Workstack.isEmpty()) {
- int element = Workstack.pop(); //retrieving each element and saving it in variable
- }
- }
- }
- }
Add new comment
- 330 views