Tech Qu: Implement a Stack as a Linked List

This is very much a low value question in the C# world because both exists in out standard library.

An implementation is shown below. Additional items like Top, IsEmpty are easy adds.

Code Snippet
  1. public class MyStack<T> : LinkedList<T>
  2.   {
  3.     public void Push(T item)
  4.     {
  5.       this.AddFirst(item);
  6.     }
  7.     public T Pop()
  8.     {
  9.       T result = this.First();
  10.       this.RemoveFirst();
  11.       return result;
  12.     }
  13.     public T Peek()
  14.     {
  15.       return this.First();
  16.     }
  17.   }

Test Cases

Code Snippet
  1. var test = new MyStack<int>();
  2.     test.Push(1);
  3.     test.Push(2);
  4.     Console.WriteLine(test.Peek());
  5.     Console.WriteLine(test.Pop());
  6.     Console.WriteLine(test.Pop());

With the console showing 2,2,1 as expected.

Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape