Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 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.    
  10.  
  11.     public class LimitedSizeStack<T>
  12.     {
  13.  
  14.         class StackItem
  15.         {
  16.             public StackItem(T item)
  17.             {
  18.                 this.item = item;
  19.             }
  20.             public T item;
  21.             public StackItem NextItem;
  22.             public StackItem LastItem;
  23.         }
  24.  
  25.         public LimitedSizeStack(int limit)
  26.         {
  27.             stackLimit = limit;
  28.         }
  29.  
  30.         int stackLimit;
  31.         StackItem head;
  32.         StackItem tail;
  33.         int stackCount;
  34.  
  35.         public void Push(T item)
  36.         {
  37.             StackItem stackItem = new StackItem(item);
  38.             if (head == null)
  39.             {
  40.                 head = tail = stackItem;
  41.                 stackCount++;
  42.             }
  43.             else
  44.             {
  45.                 tail.NextItem = stackItem;
  46.                 stackItem.LastItem = tail;
  47.                 tail = stackItem;
  48.                 stackCount++;
  49.             }
  50.             if (stackCount > stackLimit)
  51.             {
  52.                 head = head.NextItem;
  53.                 head.LastItem = null;
  54.                 stackCount--;
  55.             }
  56.         }
  57.  
  58.         public T Pop()
  59.         {
  60.             if (head == null) throw new InvalidOperationException();
  61.             var result = tail.item;
  62.             tail = tail.LastItem;
  63.             tail.NextItem = null;
  64.             stackCount--;
  65.             return result;          
  66.         }
  67.  
  68.         public int Count
  69.         {
  70.             get
  71.             {
  72.                 return stackCount;
  73.             }
  74.         }
  75.  
  76.  
  77.     }
  78.  
  79.    
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement