My teacher passed 2 exercises, the first was to create a simple stack ( Stack
) to run unit tests in this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Collections
{
public class Stack<T>
{
private List<T> stack = new List<T>();
private bool isEmpty = true;
private int count = 0;
private object top = null;
public bool IsEmpty
{ get { return isEmpty; } }
public int Count
{ get { return count; } }
public void Push(T obj)
{
stack.Add(obj);
count++;
top = obj;
if (isEmpty)
isEmpty = false;
}
public T Pop()
{
if (!isEmpty)
{
T element = stack.Last();
stack.RemoveAt(stack.Count -1);
count--;
if (count == 0)
isEmpty = true;
return element;
}
else
throw new InvalidOperationException();
}
public object Peek()
{
if (top == null)
throw new InvalidOperationException();
else
return top;
}
public void Clear()
{
stack.Clear();
isEmpty = true;
count = 0;
}
}
}
The class was created, the test class and a client class as well.
The second question is that the teacher asked to modify the class Stack
that we wrote for the following purposes:
Modifications to be made:
You must modify the stack so that it can stack priority elements . The method PushPrioritaire()
stacks an element with high priority. In the pop
method, priority elements are first pegged.
Important: Since this class is already used in its original form, it should be ensured that normal operation is not modified by
add
Features to add:
-
PrioritaireIsEmpty()
: Returns a truebool
if the stack does not contain priority elements. -
PushPrioritaire()
: Stacks a priority element.
And I have no idea how to write these new functions. The only thing I could think of was to implement a IComparable
in obj
and return:
// obj 1 > obj 2 return > 0 (1)
// obj 1 < obj 2 return < 0 (-1)
// obj 1 == obj 2 return 0
But everything I wrote thinking about it resulted in an error.