线性表的顺序存储:指在内存中用地址连续的一块存储空间顺序存放线性表的各元素,用这种存储形式存储的线性表称其为顺序表。因为内存中的地址空间是线性的,因此,用物理上的相邻实现数据元素之间的逻辑相邻关系是既简单,又自然的。
//顺序表存储结构定义
typedef int ElemType;
#define maxSize 100
typedef struct tagSeqList
{
ElemType data[maxSize];
int length;
tagSeqList()
{
memset(data, 0, sizeof(ElemType)*maxSize);
length = 0;
//或者初始化使用
//memset(this, 0, sizeof(tagSeqList));
}
}SeqList;
void print(SeqList L)
{
printf("current seql length is %d\n", L.length);
for (int i = 0; i < L.length; i++)
{
printf("%d\t", L.data[i]);
}
printf("\n");
}
//插入操作
int Insert(SeqList& L, int index, ElemType x)
{
//判断初始数组长度和插入位置的合法性
if (L.length >= maxSize) //这里是>= 不是>
{
printf("data flow\n");
return -1;
}
if (index<1 || index>L.length + 1)
{
printf("wrong position\n");
return -1;
}
//从后往前
for (int i = L.length; i >= index; i--)
L.data[i] = L.data[i-1];
L.data[index - 1] = x;
L.length++;
return 1;
}
//删除操作
int Delete(SeqList& L, int index, ElemType& value)
{
//没有判断长度为0
if (L.length == 0)
{
printf("under flow\n");
return -1;
}
if (index<1 || index>L.length)
{
printf("invalid index \n");
return -1;
}
value = L.data[index - 1];
for (int i = index - 1; i < L.length-1; i++)
{
L.data[i] = L.data[i+1];
}
//modify length
L.length--;
return 1;
}
/**
*查找操作
*/
//按位查找
int Get(SeqList L, int index,ElemType& value)
{
if (index<1 || index<L.length)
{
printf("invalid index \n");
return -1;
}
value = L.data[index - 1];
return 1;
}
//按值查找
int Locate(SeqList L, ElemType x,int& index)
{
if (L.length < 1)
{
printf("invalid Seqlist\n");
return -1;
}
for (int i = 0; i < L.length; i++)
{
if (x == L.data[i])
index = i + 1;
}
return 1;
}
// 顺序表逆置
void swap(ElemType&a,ElemType &b)
{
ElemType temp = a;
a = b;
b = temp;
}
int Reverse(SeqList& L)
{
int length = L.length ;
for (int i = 0; i < length/2; i++)
{
swap(L.data[i], L.data[length - 1 - i]);
}
return 1;
}
///判断回文 于顺序置逆相似
int BringBack(char ch[], int n)
{
for (int i = 0; i < n / 2; i++)
{
if (ch[i] != ch[n - i - 1])
return 0;
return 1;
}
}
//循环左移K个元素,重写reverse 起始位置到开始位置的逆置
void Reverse(SeqList& L, int from, int to)
{
if (to < from || to>L.length)
printf("invalid index\n");
for (int i = 0; i < (to - from + 1) / 2; i++)
{
swap(L.data[from + i], L.data[to - i]);
}
}
void Converse(SeqList&L, int n, int k)//循环左移k
{
Reverse(L, 0, k - 1);
Reverse(L, k , n - 1);
Reverse(L, 0, n - 1);
}
int _tmain(int argc, _TCHAR* argv[])
{
SeqList L ;
//Insert(L, 0, 2);
Insert(L, 1, 1);
Insert(L, 2, 3);
Insert(L, 3, 7);
Insert(L, 4, 8);
/*ElemType value;
Delete(L, 2, value);
int index;
Locate(L, 5, index);
printf("index=%d", index);*/
print(L);
//Reverse(L);
Converse(L, L.length, 1);
print(L);
getchar();
return 0;
}