CRL中的线性表
1.简单介绍
c#1.1 提供了一个非泛型接口的IList接口,接口中的项是Object,实现该接口的子类有:ArrayList,ListDictionary,StringCollection,StringDictionary
c#2.0提供泛型的IList<T>接口,实现该接口的有List<T>
2.使用介绍
using System;
using System.Collections.Generic;
namespace List
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
List<string> strList = new List<string>();
strList.Add("090897");
strList.Add("0909784374");
strList.Add("4352");
Console.WriteLine(strList[0]);
strList.Remove(strList[1]);
Console.WriteLine(strList.Count);
strList.Clear();
}
}
}
3.线性表的接口定义
public interface IListDS<T>
{
int GetLength();//求长度
void Clear();//清空操作
bool IsEmpty();//判断线性表是否为空
void Add(T item);//附加操作
void Insert(T item, int i);//插入操作
T Delete(int i);//删除操作
T GetElem(int i);//取表元
T this[int index] { get; }//定义一个索引器获取元素
int Locate(T value);//按值查找
}
4.实现方式
顺序表:顺序存储,指在内存中用一块地址连续的空间依次存放线性表的数据元素。
特点,可以任意存取。
单链表(双向链表、循环链表)
5.简单实现
using System;
using System.Collections.Generic;
using System.Text;
namespace List
{
class seqList<T> : IlistDS<T>
{
private T[] data;
private int count = 0;
public seqList(int size)
{
data = new T[size];
count = 0;
}
public seqList():this(10)
{
}
public T this[int index]
{
get { return GetEle(index); }
}
public void Add(T item)
{
//throw new NotImplementedException();
if (count == data.Length)
{
Console.WriteLine("当前顺序表已经存满,不能存入新的数据");
}
else
{
data[count] = item;
count++;
}
}
public void Clear()
{
//throw new NotImplementedException();
count = 0;
}
public T GetEle(int index)
{
//throw new NotImplementedException();
if (index >= 0 && index <= count - 1)
{
return data[index];
}
else
{
Console.WriteLine("索引不存在");
return default(T);
}
}
public int GetLength()
{
//throw new NotImplementedException();
return count;
}
public void insert(T item, int index)
{
//throw new NotImplementedException();
for (int i = count-1; i >= index; i--)
{
data[i + 1] = data[i];
}
data[index] = item;
count++;
}
public T Delete(int index)
{
//throw new NotImplementedException();
T temp = data[index];
for (int i = index+1; i < count; i++)
{
data[i - 1] = data[i];
}
count--;
return temp;
}
public bool IsEmpty()
{
//throw new NotImplementedException();
return count == 0;
}
public int Locate(T value)
{
//throw new NotImplementedException();
for (int i = 0; i < count; i++)
{
if (data[i].Equals(value))
{
return i;
}
}
return -1;
}
}
}
using System;
using System.Collections.Generic;
namespace List
{
class Program
{
static void Main(string[] args)
{
seqList<string> s = new seqList<string>();
s.Add("1234");
s.Add("67");
Console.WriteLine(s.GetEle(0));
for (int i = 0; i < s.GetLength(); i++)
{
Console.Write(s[i] + " ");
}
}
}
interface IlistDS<T>
{
int GetLength();
void Clear();
bool IsEmpty();
void Add(T item);
void insert(T item, int index);
T Delete(int index);
T this[int index] { get; }
T GetEle(int index);
int Locate(T value);
}
}