Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace CP
- {
- internal class MyStack
- {
- #region(Fields)
- private string[] items;
- private int top = -1;
- #endregion
- #region(Properties)
- public int Capacity => items.Length;
- public int Count => top + 1;
- #endregion
- #region(Constructors)
- public MyStack()
- {
- items = new string[4];
- }
- public MyStack(IEnumerable<string> collection)
- {
- items = collection.Reverse().ToArray();
- top = items.Length - 1;
- }
- #endregion
- #region(Methods)
- public void Push(string item)
- {
- if (Count == Capacity)
- {
- Resize(Capacity * 2);
- }
- items[++top] = item;
- }
- public string Pop()
- {
- if (Count == 0)
- {
- throw new InvalidOperationException("Stack is empty.");
- }
- string item = items[top];
- items[top--] = default;
- return item;
- }
- public string Peek()
- {
- if (Count == 0)
- {
- throw new InvalidOperationException("Stack is empty.");
- }
- return items[top];
- }
- public string[] ToArray()
- {
- string[] arr = new string[Count];
- for (int i = 0; i <= top; i++)
- {
- arr[Count - 1 - i] = items[i];
- }
- return arr;
- }
- public void Clear()
- {
- for (int i = 0; i <= top; i++)
- {
- items[i] = default;
- }
- top = -1;
- }
- public bool Contains(string item)
- {
- for (int i = 0; i <= top; i++)
- {
- if (items[i] == item)
- {
- return true;
- }
- }
- return false;
- }
- public IEnumerable<string> Concat(IEnumerable<string> collection)
- {
- return this.ToArray().Concat(collection);
- }
- public IEnumerable<string> Append(string item)
- {
- return this.ToArray().Append(item);
- }
- public string ElementAt(int index)
- {
- if (index < 0 || index >= Count)
- {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- return items[top - index];
- }
- public void CopyTo(string[] array, int arrayIndex)
- {
- if (array == null)
- {
- throw new ArgumentNullException(nameof(array));
- }
- if (arrayIndex < 0 || arrayIndex + Count > array.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(arrayIndex));
- }
- for (int i = 0; i < Count; i++)
- {
- array[arrayIndex + i] = items[Count - 1 - i];
- }
- }
- private void Resize(int newSize)
- {
- string[] newItems = new string[newSize];
- Array.Copy(items, 0, newItems, 0, Count);
- items = newItems;
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement