常见容器的实现方法,用数组实现一个栈、队列、动态数组

队列的实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/// <summary>
/// 使用循环队列,在尾部入队,在头部出队
/// 考虑的问题:如何区分队空、队满,头尾指针指向哪里
/// </summary>
public class Queue
{
    private int[] data;
    private int capacity;
    private int front;
    private int rear;

    public Queue(int cap)
    {
        data = new int[cap];
        capacity = cap;
        front = 0;
        rear = 0;
    }

    public int Count
    {
        get { return (capacity + rear - front) % capacity; }
    }

    public void Push(int value)
    {
        if (!IsEmpty())
        {
            data[rear] = value;
            rear = (rear + 1) % capacity;
        }
        else
        {
            throw new Exception("push failed");
        }
    }

    public int Pop()
    {
        int v = data[front];
        front = (front + 1) % capacity;
        return v;
    }

    public bool IsEmpty ()
    {
        return (Count + 1) == capacity;
    }

    public IEnumerator GetEnumerator()
    {
        int i = front;
        while (i != rear)
        {
            yield return data[i];
            i = (i + 1) % capacity;
        }
    }
}