mirror of
https://github.com/krahets/hello-algo.git
synced 2026-05-12 11:37:08 +08:00
Add build scripts for C# and
unify the coding style.
This commit is contained in:
@@ -854,103 +854,7 @@ comments: true
|
||||
=== "C#"
|
||||
|
||||
```csharp title="my_list.cs"
|
||||
class MyList
|
||||
{
|
||||
private int[] nums; // 数组(存储列表元素)
|
||||
private int capacity = 10; // 列表容量
|
||||
private int size = 0; // 列表长度(即当前元素数量)
|
||||
private int extendRatio = 2; // 每次列表扩容的倍数
|
||||
|
||||
/* 构造函数 */
|
||||
public MyList()
|
||||
{
|
||||
nums = new int[capacity];
|
||||
}
|
||||
|
||||
/* 获取列表长度(即当前元素数量)*/
|
||||
public int Size()
|
||||
{
|
||||
return size;
|
||||
}
|
||||
|
||||
/* 获取列表容量 */
|
||||
public int Capacity()
|
||||
{
|
||||
return capacity;
|
||||
}
|
||||
|
||||
/* 访问元素 */
|
||||
public int Get(int index)
|
||||
{
|
||||
// 索引如果越界则抛出异常,下同
|
||||
if (index < 0 || index >= size)
|
||||
throw new IndexOutOfRangeException("索引越界");
|
||||
return nums[index];
|
||||
}
|
||||
|
||||
/* 更新元素 */
|
||||
public void Set(int index, int num)
|
||||
{
|
||||
if (index < 0 || index >= size)
|
||||
throw new IndexOutOfRangeException("索引越界");
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* 尾部添加元素 */
|
||||
public void Add(int num)
|
||||
{
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (size == Capacity())
|
||||
ExtendCapacity();
|
||||
nums[size] = num;
|
||||
// 更新元素数量
|
||||
size++;
|
||||
}
|
||||
|
||||
/* 中间插入元素 */
|
||||
public void Insert(int index, int num)
|
||||
{
|
||||
if (index < 0 || index >= size)
|
||||
throw new IndexOutOfRangeException("索引越界");
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if (size == Capacity())
|
||||
ExtendCapacity();
|
||||
// 将索引 index 以及之后的元素都向后移动一位
|
||||
for (int j = size - 1; j >= index; j--)
|
||||
{
|
||||
nums[j + 1] = nums[j];
|
||||
}
|
||||
nums[index] = num;
|
||||
// 更新元素数量
|
||||
size++;
|
||||
}
|
||||
|
||||
/* 删除元素 */
|
||||
public int Remove(int index)
|
||||
{
|
||||
if (index < 0 || index >= size)
|
||||
throw new IndexOutOfRangeException("索引越界");
|
||||
int num = nums[index];
|
||||
// 将索引 index 之后的元素都向前移动一位
|
||||
for (int j = index; j < size - 1; j++)
|
||||
{
|
||||
nums[j] = nums[j + 1];
|
||||
}
|
||||
// 更新元素数量
|
||||
size--;
|
||||
// 返回被删除元素
|
||||
return num;
|
||||
}
|
||||
|
||||
/* 列表扩容 */
|
||||
public void ExtendCapacity()
|
||||
{
|
||||
// 新建一个长度为 size 的数组,并将原数组拷贝到新数组
|
||||
System.Array.Resize(ref nums, Capacity() * extendRatio);
|
||||
// 更新列表容量
|
||||
capacity = nums.Length;
|
||||
}
|
||||
}
|
||||
[class]{MyList}-[func]{}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
Reference in New Issue
Block a user