4
My teacher passed 2 exercises, the first was to create a stack (Stack
) simple 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 write for the following purposes:
Modifications to be made:
You must modify the stack so that it can be stacked priority elements. The method PushPrioritaire()
stack an element with high priority. In the method pop
, the priority elements are stacked first.
Important: Since this class is already used in its original form, it must be ensured that the usual operation is not modified by
add
feature.
Features to add:
PrioritaireIsEmpty()
: Returns abool
true if the battery does not contain priority elements.PushPrioritaire()
: Stack 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
us 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 was wrong.
I could leave the method code here
PushPrioritaire()
?– CypherPotato
@Cypherpotato this code I didn’t write ... Everything I wrote has errors everywhere
– Marcelo Medeiros dos Santos