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
- public class MyStack<T> : LinkedList<T>
- {
- public void Push(T item)
- {
- this.AddFirst(item);
- }
- public T Pop()
- {
- T result = this.First();
- this.RemoveFirst();
- return result;
- }
- public T Peek()
- {
- return this.First();
- }
- }
Test Cases
Code Snippet
- var test = new MyStack<int>();
- test.Push(1);
- test.Push(2);
- Console.WriteLine(test.Peek());
- Console.WriteLine(test.Pop());
- Console.WriteLine(test.Pop());
With the console showing 2,2,1 as expected.
Comments
Post a Comment