Define Stack and its operations. Write java program to perform stack operations. (Explanation, Algorithm, Java source code)
时间: 2024-02-18 16:05:25 浏览: 80
A stack is a linear data structure that follows a particular order in which the operations are performed. The order is known as LIFO (Last In First Out). This means that the element which is pushed last onto the stack will be the first one to be popped off the stack.
Stack operations include:
1. push - adds an element to the top of the stack
2. pop - removes the top element from the stack
3. peek - returns the top element of the stack without removing it
4. isEmpty - checks if the stack is empty
5. isFull - checks if the stack is full
Java program to perform stack operations:
```
class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (isFull()) {
System.out.println("Stack is full!");
return;
}
top++;
stackArray[top] = value;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty!");
return -1;
}
int temp = stackArray[top];
top--;
return temp;
}
public int peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
}
public class Main {
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Top element: " + stack.peek());
stack.push(40);
stack.push(50);
System.out.println("Full: " + stack.isFull());
while (!stack.isEmpty()) {
int value = stack.pop();
System.out.println(value);
}
System.out.println("Empty: " + stack.isEmpty());
}
}
```
Explanation:
In this program, we have defined a `Stack` class that contains all the necessary stack operations - `push`, `pop`, `peek`, `isEmpty`, and `isFull`. The `Stack` class also has three instance variables - `maxSize`, `stackArray`, and `top`.
In the `push` method, we first check if the stack is already full. If it is, we print a message and return. Otherwise, we increment the `top` variable and add the new element to the `stackArray`.
In the `pop` method, we first check if the stack is empty. If it is, we print a message and return -1. Otherwise, we retrieve the top element from the `stackArray`, decrement the `top` variable, and return the element.
In the `peek` method, we simply return the top element from the `stackArray`.
In the `isEmpty` method, we check if the `top` variable is -1, which means the stack is empty.
In the `isFull` method, we check if the `top` variable is equal to `maxSize - 1`, which means the stack is full.
In the `Main` class, we create a new `Stack` object with a maximum size of 5. We then push some elements onto the stack, print the top element, push some more elements, and finally pop all the elements off the stack and print them.
阅读全文