Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Task1
- {
- class Program
- {
- static void Main()
- {
- Stack stack = new();
- stack.Push(10);
- stack.Push(20);
- stack.Push(30);
- stack.ShowStack();
- Console.WriteLine($"Верхний элемент: {stack.Top()}");
- stack.Pop();
- stack.ShowStack();
- while (!stack.IsEmpty())
- {
- stack.Pop();
- }
- stack.Pop();
- }
- public class Stack
- {
- private readonly int[] _stackArray;
- private readonly int _capacity;
- private int _topIndex;
- public Stack(int size = 10)
- {
- _capacity = size;
- _stackArray = new int[_capacity];
- _topIndex = -1;
- }
- public bool IsEmpty()
- {
- return _topIndex == -1;
- }
- public void Push(int value)
- {
- if (_topIndex >= _capacity - 1)
- {
- Console.WriteLine("Ошибка: стек переполнен.");
- return;
- }
- _topIndex++;
- _stackArray[_topIndex] = value;
- Console.WriteLine($"Элемент {value} добавлен в стек.");
- }
- public int Pop()
- {
- if (IsEmpty())
- {
- Console.WriteLine("Ошибка: стек пуст. Невозможно извлечь элемент.");
- return 0;
- }
- int value = _stackArray[_topIndex];
- _topIndex--;
- Console.WriteLine($"Элемент {value} удалён из стека.");
- return value;
- }
- public int Top()
- {
- if (IsEmpty())
- {
- Console.WriteLine("Ошибка: стек пуст. Нет верхнего элемента.");
- return 0;
- }
- return _stackArray[_topIndex];
- }
- public void ShowStack()
- {
- if (IsEmpty())
- {
- Console.WriteLine("Стек пуст.");
- return;
- }
- Console.Write("Содержимое стека: ");
- for (int i = _topIndex; i >= 0; i--)
- {
- Console.Write($"{_stackArray[i]} ");
- }
- Console.WriteLine();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement