Advertisement
Guest User

Untitled

a guest
Feb 17th, 2019
467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.89 KB | None | 0 0
  1. using System;
  2.  
  3. namespace TodoApplication
  4. {
  5.     public class LimitedSizeStack<T>
  6.     {
  7.         private readonly T[] array;
  8.         private int offset = -1;
  9.         private int count;
  10.    
  11.         public LimitedSizeStack(int limit)
  12.         {
  13.             array = new T[limit];
  14.         }
  15.  
  16.         public void Push(T item)
  17.         {
  18.             offset++;
  19.            
  20.             count++;
  21.             if (count > array.Length)
  22.                 count = array.Length;
  23.            
  24.             array[offset % array.Length] = item;
  25.         }
  26.  
  27.         public T Pop()
  28.         {
  29.             count--;
  30.            
  31.             if (count < 0)
  32.                 throw new InvalidOperationException("stack is empty");
  33.            
  34.             var value = array[offset % array.Length];
  35.  
  36.             offset--;
  37.  
  38.             return value;
  39.         }
  40.  
  41.         public int Count => count;
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement