// Program (Main)
var s = new UniqueStack<int>();
s.Push(3);
s.Push(2);
s.Push(1);
s.Push(1); // Exception
while (s.Count > 0)
{
Console.WriteLine(s.Pop()); // 1->2->3
}
I want to bring this Code to life. I had a very similiar task once and tried to make it for this task works, but it didn't works well, because I have some parts of it as blanks, because i dont know how to go forward.
// UniqueStack (Class)
using System;
using System.Collections;
namespace StackTest
{
internal class UniqueStack<T> : ICollection
{
private ArrayList<T> items = new ArrayList<T>();
public int Count
{
get { return items.Count; }
}
public UniqueStack()
{
}
public void Push(T item)
{
items.Add(item);
}
public T Pop()
{
T item;
if (items.Count == 0)
throw new InvalidOperationException("No items in stack");
item = items[items.Count - 1];
items.RemoveAt(items.Count - 1);
return item;
}
}
}
I clearly see, that this Code didn't throw an exception, when its a clone of a existing pushed number. And my ICollection don't work for this example, because the code doesn't work with it. Any one who can help an very poor skilled programer?
Thank you!
internal class UniqueStack<T>
{
private List<T> items = new List<T>();
public int Count
{
get { return items.Count; }
}
public UniqueStack()
{
}
public void Push(T item)
{
if (items.Contains(item))
{
throw new System.InvalidOperationException("Doppelte Werte sind nicht erlaubt!");
}
items.Add(item);
}
public T Pop()
{
T item;
if (items.Count == 0)
throw new InvalidOperationException("No items in stack");
item = items[items.Count - 1];
items.RemoveAt(items.Count - 1);
return item;
}
public override string ToString()
{
string s = "";
while (items != null)
{
s += items.ToString() + " -> ";
}
s += "Count: " + Count.ToString();
return s;
}
}
My code does work, but I can't display it right. It says 1 2 3
Instead of 1 - > 2 - > 3