我有这个问题,我一直在试图弄清楚。我试图让 CustomStack 像 Stack 一样,只实现 Push(T)、Pop()、Peek() 和 Clear() 方法。我有这段代码,我认为它是正确的,但输出只显示了一半的数字。我认为这与push方法有关,但我看不出它有什么问题。
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace Enumerator
{
class Program
{
static void Main(string[] args)
{
CustomStack<int> collection = new CustomStack<int>();
for (int i = 0; i < 30; i++)
{
collection.Push(i);
Console.WriteLine(collection.Peek());
}
collection.Push(23);
foreach (int x in collection)
{
Console.WriteLine(collection.Pop());
}
Console.WriteLine("current", collection.Peek());
Console.ReadKey();
}
}
public class CustomStack<T> : IEnumerable<T>
{
private T[] arr;
private int count;
public CustomStack()
{
count = 0;
arr = new T[5];
}
public T Pop()
{
int popIndex = count;
if (count > 0)
{
count--;
return arr[popIndex];
}
else
{
return arr[count];
}
}
public void Push(T item)
{
count++;
if (count == arr.Length)
{
Array.Resize(ref arr, arr.Length + 1);
}
arr[count] = item;
}
public void Clear()
{
count = 0;
}
public T Peek()
{
return arr[count];
}
public int Count
{
get
{
return count;
}
}
public IEnumerator<T> GetEnumerator()
{
return new MyEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new MyEnumerator(this);
}
public class MyEnumerator : IEnumerator<T>
{
private int position;
private CustomStack<T> stack;
public MyEnumerator(CustomStack<T> stack)
{
this.stack = stack;
position = -1;
}
public void Dispose()
{
}
public void Reset()
{
position = -1;
}
public bool MoveNext()
{
position++;
return position < stack.Count;
}
Object IEnumerator.Current
{
get
{
return stack.arr[position];
}
}
public T Current
{
get
{
return stack.arr[position];
}
}
}
}
}