Advertisement
WilleMahMille

Exempel - Generics + Länkad lista

Jan 17th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. namespace Generics {
  2.     class Program {
  3.  
  4.         static void Main(string[] args) {
  5.  
  6.             MyStack<int> stack = new MyStack<int>();
  7.             Random rand = new Random();
  8.  
  9.             for (int i = 0; i < 5; i++)
  10.                 stack.EnQueue(rand.Next(1000));
  11.  
  12.             for(int i = 1; i <= stack.length; i++)
  13.                 Console.WriteLine(i + ": " + stack.At(i - 1));
  14.             Console.WriteLine("Popping");
  15.             for(int i = stack.length; i > 0; i--)
  16.                 Console.WriteLine(stack.DeQueue());
  17.  
  18.             Console.ReadKey(true);
  19.         }
  20.  
  21.     }
  22.     class ElementInStack<T> {
  23.         public ElementInStack(T value){
  24.             this.value = value;
  25.         }
  26.  
  27.         public T value;
  28.         public ElementInStack<T> next;
  29.         public T At(int index) {
  30.             if (index == 0)
  31.                 return value;
  32.             if (next == null)
  33.                 throw new Exception("Index out of range");
  34.             return next.At(index - 1);
  35.         }
  36.     }
  37.  
  38.     class MyStack<T> {
  39.         ElementInStack<T> first;
  40.         ElementInStack<T> last;
  41.         public int length { get; private set; }
  42.         public MyStack() {
  43.             length = 0;
  44.         }
  45.  
  46.         public void EnQueue(T value) {
  47.             ElementInStack<T> element = new ElementInStack<T>(value);
  48.             length++;
  49.             if (first == null) {
  50.                 first = element;
  51.                 last = first;
  52.             }
  53.             else {
  54.                 last.next = element;
  55.                 last = element;
  56.             }
  57.         }
  58.         public T DeQueue() {
  59.             if(first == null)
  60.                 throw new Exception("Stack empty");
  61.             else {
  62.                 length--;
  63.                 T temp = first.value;
  64.                 first = first.next;
  65.                 return temp;
  66.             }
  67.         }
  68.         public T At(int index) {
  69.             return first.At(index);
  70.         }
  71.  
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement