我有這個問題,我一直在試圖弄清楚。 我試圖使CustomStack行爲像堆棧,只實現Push(T),Pop(),Peek()和Clear()方法。我有這個代碼,我認爲這是正確的,但輸出只顯示一半的數字。我認爲這與推送方法有關,但我看不出它有什麼問題。自定義堆棧<T> IEnumerable <T>和數組?
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];
}
}
}
}
}
您是否花費了精力進行調試?只需一步一步,看看會發生什麼。 – 2013-05-11 06:23:51
此問題被關閉爲「太本地化」;我不同意這種評估。我看到有多人犯這個錯誤。 (修改迭代集合的一般錯誤,以及在迭代它時彈出堆棧的特定錯誤,並且僅得到一半元素) – 2013-05-14 17:07:10