Write java program to perform stack operations. (Explanation, Algorithm, Java source code)
时间: 2024-02-15 15:03:19 浏览: 80
Sure, here's an explanation, algorithm, and Java source code for a basic stack implementation:
Explanation:
A stack is a data structure that allows elements to be added and removed only from the top of the stack. It follows the LIFO (last-in, first-out) principle. The basic operations performed on a stack include push, pop, and peek.
Algorithm:
1. Create a class called Stack with an array to hold the elements, a variable to keep track of the top of the stack, and a constructor to initialize the stack.
2. Implement the push operation by adding an element to the top of the stack and incrementing the top variable.
3. Implement the pop operation by removing the element from the top of the stack, decrementing the top variable, and returning the removed element.
4. Implement the peek operation by returning the element at the top of the stack without removing it.
5. Implement a method to check if the stack is empty by checking if the top variable is equal to -1.
Java Source Code:
```
public class Stack {
private int[] elements;
private int top;
public Stack(int size) {
elements = new int[size];
top = -1;
}
public void push(int element) {
if (top == elements.length - 1) {
System.out.println("Stack overflow error!");
} else {
elements[++top] = element;
}
}
public int pop() {
if (top == -1) {
System.out.println("Stack underflow error!");
return -1;
} else {
return elements[top--];
}
}
public int peek() {
if (top == -1) {
System.out.println("Stack is empty!");
return -1;
} else {
return elements[top];
}
}
public boolean isEmpty() {
return (top == -1);
}
}
```
This implementation uses an array to hold the elements in the stack. The push and pop operations increment and decrement the top variable, respectively, to keep track of the top of the stack. The peek operation returns the element at the top of the stack without removing it. The isEmpty method checks if the top variable is equal to -1, which indicates an empty stack.
阅读全文