1 数组
1.1 C#中的数组
静态数组:int[] float[] double[] char[] string[]
特点:创建后容量无法改变
例如:
int[] arr = new int[10]
动态数组:ArrayList List(泛型)
特点:根据元素的数量,动态地调整数组的容量大小
class Program
{
static void Main(string[] args)
{
//数组
int[] arr = new int[10];
for (int i = 0; i < 10; i++)
{
arr[i] = i;
Console.Write(arr[i] + " ");
}
Console.WriteLine();
//动态数组ArrayList
ArrayList a = new ArrayList(10);
for (int i = 0; i < 15; i++)
{
a.Add(i);
Console.Write(a[i] + " ");
}
Console.WriteLine();
//泛型动态数组
List<int> l = new List<int>(10);
for (int i = 0; i < 15; i++)
{
l.Add(i);
Console.Write(l[i] + " ");
}
Console.Read();
}
}
1.2 实现一个存储整型元素的动态数组
using System;
using System.Collections.Generic;
using System.Text;
namespace DataStructure
{
class Array1//编写动态数组框架
{
private int[] data;//存储元素的静态数组data
private int N;//存储元素个数N
public Array1(int capacity)//有参构造
{
data = new int[capacity];
N = 0;
}
public Array1() : this(10) {
}//无参构造
//public Array1()
//{
// data = new int[10];
// N = 0;
//}
private void ResetCapacity(int newCapacity)//重构数组容量,并把原有元素存储
{
int[] newData = new int[newCapacity];
for (int i = 0; i < N; i++)
newData[i] = data[i];
data = newData;
}
public int Capacity//获取数组容量
{
get {
return data.Length; }
}
public int Count//获取数组元素个数
{
get {
return N; }
}
public bool IsEmpty//判断数组是否为空
{
get {
return N == 0; }
}
public void Add(int index,int e)//添加元素到数组中的指定索引位置
{
if (index < 0 || index > N)//判断索引位置是否合法
throw new ArgumentException("数组索引越界");
if (N == data.Length)//判断数组容量是否满了
ResetCapacity(2 * data.Length);
for (int i= N-1;i >= index; i--)//从数组末尾向后移动元素
data[i + 1] = data[i];
data[index] = e;
N++;
}
public void AddLast(int e)//数组末尾添加元素
{
Add(N, e);
}
public void AddFirst(int e)//数组头部添加元素
{
Add(0, e);
}
public int Get