Advertisement
Schnuk

Untitled

Mar 6th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.15 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace TodoApplication
  8. {
  9.     public class LimitedSizeStack<T>
  10.     {
  11.         LimitedSizeStackItem<T> head;
  12.         LimitedSizeStackItem<T> tail;
  13.         int count;
  14.         int stackLimit;
  15.  
  16.         public LimitedSizeStack(int limit)
  17.         {
  18.             stackLimit = limit;
  19.         }
  20.  
  21.         public void Push(T item)
  22.         {  
  23.             if (!isLimitZero())
  24.             {
  25.                 if (head == null)
  26.                 {
  27.                     tail = head = new LimitedSizeStackItem<T> { Item = item, Next = null, Previous = null };
  28.                     count++;
  29.                 }
  30.                 else
  31.                 {
  32.                     if (isStackFull())
  33.                     {
  34.                         head = head.Next;
  35.                         head.Previous = null;
  36.                     }
  37.                     else
  38.                         count++;
  39.                     var stackItem = new LimitedSizeStackItem<T> { Item = item, Next = null, Previous = tail };
  40.                     tail.Next = stackItem;
  41.                     tail = stackItem;
  42.                 }
  43.             }
  44.         }
  45.  
  46.         public T Pop()
  47.         {
  48.             if (!isLimitZero() && count != 0)
  49.             {
  50.                 var result = tail.Item;
  51.                 count--;
  52.                 if (tail != head)
  53.                     tail = tail.Previous;
  54.                 if (head == null)
  55.                     tail = null;
  56.                 return result;
  57.             }
  58.             return default;
  59.         }
  60.  
  61.         public int Count
  62.         {
  63.             get
  64.             {
  65.                 return count;
  66.             }
  67.         }
  68.  
  69.         private bool isStackFull()
  70.         {
  71.             return count == stackLimit;
  72.         }
  73.  
  74.         private bool isLimitZero()
  75.         {
  76.             return stackLimit == 0;
  77.         }
  78.     }
  79.  
  80.     public class LimitedSizeStackItem<T>
  81.     {
  82.         public T Item { get; set; }
  83.         public LimitedSizeStackItem<T> Next { get; set; }
  84.         public LimitedSizeStackItem<T> Previous { get; set; }
  85.     }
  86. }
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement