本文主要介绍线性表的逻辑结构、存储结构和相关运算,以及应用实例。
一、基础知识
1. 定义
由n个数据特性相同的元素构成的有限序列称为线性表。
2. 特点
非空的线性表或线性结构,其特点包括:
- 存在唯一的一个被称作“第一个”的数据元素;
- 存在唯一的一个被称作“最后一个”的数据元素;
- 除第一个之外,结构中每个数据元素均只有一个前驱;
- 除最后一个元素外,结构中每个数据元素只有一个后继。
3. 常见函数
InitList(&L)
DestroyList(&L)
ClearList(&L)
ListEmpty(L)
ListEmpty(L)
GetElem(L,i,&e)
LocateElem(L,e)
PriorElem(L,cur_e,&pre_e)//返回前驱
NextElem(L,cur_e,&next_e)//返回后继
ListInsert(&L,i,e)
ListDelete(&L,i)
TraverseList(L)//遍历
二、 线性表的顺序存储表示
线性表的顺序表示指的是用一组地址连续的存储单元依次存储线性表的数据元素,这种表示也称作线性表的顺序存储结构或顺序映像。通常,称这种存储结构的线性表为顺序表。其特点是,逻辑上相邻的数据元素,物理次序也是相邻的。
设每个元素占 l 个单元,以第一个单元的存储地址作为数据元素的存储起始位置。即线性表的位置 = 基址 + 所有元素占的存储单元。
LOC(ai+1)=LOC(ai)+l;
一般而言,线性表的第 i 个数据元素ai的存储位置为:
LOC(ai)=LOC(a1)+(i-1)*l;

图1 线性表的顺序存储结构图
三、 顺序表的基本操作实现
public class Linelist
{
public string[] data
{
get;
set;
}
public int length{
get;
set;
}
public Linelist(string[] data,int legnth)
{
this.data = data;
this.length = length;
}
public static int n = 100;//定义全局静态变量
/// <summary>
/// 获取线性表中的某个元素
/// </summary>
/// <param name="list">列表</param>
/// <param name="i">元素位置</param>
/// <param name="e">待查找元素</param>
/// <returns></returns>
public static string getElement(Linelist list,int i,string e)
{
if (i < 1 || i > n)
{
return "false";
}
e = list.data[i];
return e;
}
/// <summary>
/// 在顺序表中查找元素e是否存在
/// </summary>
/// <param name="list"></param>
/// <param name="e"></param>
/// <returns></returns>
public static int Search(Linelist list,string e)
{
for(int i = 0; i < list.length; i++)
if (list.data[i] == e)
return i + 1;
return 0;
}
/// <summary>
/// 向列表中添加元素
/// </summary>
/// <param name="list"></param>
/// <param name="i"></param>
/// <param name="e"></param>
/// <returns></returns>
public static int Insert(Linelist list,int i,string e)
{
if (i < 1 || i > n)//如果索引值不合法
return 0;
if (list.length == n)//如果线性列表存储空间已满
return 0;
for (int j = n; j >= i + 1;i--)
{
list.data[j+1] = list.data[j];
}
list.data[i] = e;
return 1;
}
public static int delete(Linelist list,int i)
{
if (i < 1 || i > n)
return 0;
for (int j = i; j < n;j++ )
{
list.data[j-1] = list.data[j];
j--;
}
return 1;
}
}
浙公网安备 33010602011771号