OneCompiler

bc stack

124

pragma solidity ^0.8.0;

contract Stack {
uint256 constant private STACK_SIZE = 10; // Maximum size of the stack
uint256[] private stack; // Array to store stack elements
uint256 private top; // Index pointing to the top of the stack

// Constructor to initialize the stack
constructor() {
    stack = new uint256[](STACK_SIZE);
    top = 0;
}

// Function to push an element onto the stack
function push(uint256 value) public {
    require(top < STACK_SIZE, "Stack overflow");
    stack[top] = value;
    top++;
}

// Function to pop an element from the stack
function pop() public returns (uint256) {
    require(top > 0, "Stack underflow");
    top--;
    return stack[top];
}

// Function to get the top element of the stack without removing it
function peek() public view returns (uint256) {
    require(top > 0, "Stack is empty");
    return stack[top - 1];
}

// Function to check if the stack is empty
function isEmpty() public view returns (bool) {
    return top == 0;
}

}