C#数据结构之线性表

在 C# 中,线性表可以使用数组或链表等数据结构来实现。以下是使用数组实现线性表的示例:

public class ArrayList<T>
{
    private T[] _items;
    private int _size;
    private const int _defaultCapacity = 4;

    public ArrayList()
    {
        _items = new T[_defaultCapacity];
    }

    public int Count
    {
        get { return _size; }
    }

    public T this[int index]
    {
        get
        {
            if (index < 0 || index >= _size)
                throw new ArgumentOutOfRangeException(nameof(index));

            return _items[index];
        }
        set
        {
            if (index < 0 || index >= _size)
                throw new ArgumentOutOfRangeException(nameof(index));

            _items[index] = value;
        }
    }

    public void Add(T item)
    {
        if (_size == _items.Length)
        {
            EnsureCapacity(_size + 1);
        }

        _items[_size++] = item;
    }

    private void EnsureCapacity(int min)
    {
        if (_items.Length < min)
        {
            int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;
            if (newCapacity < min)
                newCapacity = min;
            Array.Resize(ref _items, newCapacity);
        }
    }

    public void Insert(int index, T item)
    {
        if (index < 0 || index > _size)
            throw new ArgumentOutOfRangeException(nameof(index));

        if (_size == _items.Length)
            EnsureCapacity(_size + 1);

        if (index < _size)
            Array.Copy(_items, index, _items, index + 1, _size - index);

        _items[index] = item;
        _size++;
    }

    public bool Remove(T item)
    {
        int index = IndexOf(item);
        if (index < 0)
            return false;

        RemoveAt(index);
        return true;
    }

    public void RemoveAt(int index)
    {
        if (index < 0 || index >= _size)
            throw new ArgumentOutOfRangeException(nameof(index));

        _size--;
        if (index < _size)
            Array.Copy(_items, index + 1, _items, index, _size - index);

        _items[_size] = default(T);
    }

    public int IndexOf(T item)
    {
        for (int i = 0; i < _size; i++)
        {
            if (Equals(_items[i], item))
                return i;
        }

        return -1;
    }

    public void Clear()
    {
        Array.Clear(_items, 0, _size);
        _size = 0;
    }
}

使用示例:

ArrayList<int> list = new ArrayList<int>();
list.Add(1);
list.Add(2);
list.Insert(1, 3);
list.Remove(2);

for (int i = 0; i < list.Count; i++)
{
    Console.WriteLine(list[i]);
}

输出:

1
3

这个示例中,使用数组作为内部数据存储结构,实现了线性表的基本操作,包括增加、删除、插入、查找等。除了使用数组来实现线性表外,还可以使用链表等数据结构来实现。

猜你喜欢

转载自blog.csdn.net/zsqf813/article/details/129733603