顺序线性表

本文介绍了线性列表的接口定义及其顺序线性表的实现。顺序线性表支持增删查改操作,包括获取长度、判断是否为空、清除元素、获取指定位置元素、插入元素、删除元素以及查找元素的功能。通过`SequentialList<T>`类实现了接口`ILinearList<T>`,并提供了异常处理来确保操作的正确性。
摘要由CSDN通过智能技术生成
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface ILinearList<T>
    {
        int Length { get; }

        bool IsEmpty();
        void Clear();
        T GetItem(int index);

        int LocateItem(T t);

        void Insert(T item, int index);

        void Add(T item);
        void Delete(int index);
    }

    /// <summary>
    /// 顺序线性表
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SequentialList<T> : ILinearList<T>
    {
        private T[] list;
        private int count = 0;

        public SequentialList(int maxSize)
        {
            list = new T[maxSize];
        }

        public int Length => count;

        public void Add(T item)
        {
            if (count == list.Length)
            {
                throw new Exception("表存储已经满了");
            }
            count++;
            list[count - 1] = item;
        }

        public void Clear()
        {
            count = 0;
        }

        public void Delete(int index)
        {
            if (index < 0 || index > count - 1)
            {
                throw new Exception("索引不正确");
            }
            count--;
            for (int i = index; i < count; i++)
            {
                list[i] = list[i + 1];
            }
        }

        public T GetItem(int index)
        {
            return list[index];
        }

        public void Insert(T item, int index)
        {
            if (count == list.Length)
            {
                throw new Exception("表存储已经满了");
            }

            if (index < 0 || index > count - 1)
            {
                throw new Exception("索引不正确");
            }
            count++;
            for (int i = count + 1; i < index; i--)
            {
                list[i] = list[i - 1];
            }
            list[index] = item;
        }

        public bool IsEmpty()
        {
            return count == 0;
        }

        public int LocateItem(T t)
        {
            for (int i = 0; i < count; i++)
            {
                if (list[i].Equals(t))
                {
                    return i;
                }
            }
            return -1;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值