恩造数据结构与算法c# 用数组实现List

实现一下List,加深一下印象,后面还有用 

using System;
using UnityEngine;

public class ArrayListExample : MonoBehaviour
{
    private int[] array;
    private int count;

    void Start()
    {
        array = new int[10];
        count = 0;

        // 添加元素
        AddElement(5);
        AddElement(10);
        AddElement(15);

        // 查找元素
        int index = FindElement(10);
        Debug.Log("Element 10 found at index: " + index);

        // 修改元素
        UpdateElement(1, 20);
        Debug.Log("Element at index 1 updated to: " + array[1]);

        // 删除元素
        RemoveElement(15);
        Debug.Log("Element 15 removed. List count: " + count);
    }

    void AddElement(int element)
    {
        if (count < array.Length)
        {
            array[count] = element;
            count++;
            Debug.Log("Added element: " + element);
        }
        else
        {
            Debug.Log("Array is full. Cannot add element.");
        }
    }

    int FindElement(int element)
    {
        for (int i = 0; i < count; i++)
        {
            if (array[i] == element)
            {
                return i;
            }
        }
        return -1; // Element not found
    }

    void UpdateElement(int index, int newElement)
    {
        if (index >= 0 && index < count)
        {
            array[index] = newElement;
            Debug.Log("Updated element at index " + index + " to " + newElement);
        }
        else
        {
            Debug.Log("Index out of range.");
        }
    }

    void RemoveElement(int element)
    {
        int index = FindElement(element);
        if (index != -1)
        {
            for (int i = index; i < count - 1; i++)
            {
                array[i] = array[i + 1];
            }
            count--;
            Debug.Log("Removed element: " + element);
        }
        else
        {
            Debug.Log("Element not found.");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值