线性表
定义
由同一类型的数据元素构成的有序序列的线性结构。
数据对象集:由n个元素构成的有序序列(a1,a2,…,an),
a
i
+
1
a_{i+1}
ai+1为
a
i
a_{i}
ai的直接后继,
a
i
−
1
a_{i-1}
ai−1是
a
i
a_i
ai的直接前驱。直接前驱和直接后驱反映了元素之间一对一的邻接关系。
操作集:
(1)L
顺序存储实现
在内存中用地址连续的一块存储空间顺序存放线性表的各元素。可用一维数组来表示顺序存储的数据域。
数据类型
typedef int position;
typedef struct LNode * PtrToLNode;
struct LNode{
ElementType Data[MAXSIZ];
Position Last;
};
typedef PtrToLNode List;
由此,我们可用利用List定义线性表L,通过L可以访问相应线性表的内容。
L->Data[i]可以得到下标为i的元素、L->Last+1可得到线性表长度。
初始化
分配空间+Last指向-1
List MakeEmpty() {
List L = (List)malloc(sizeof(struct LNode));
L->Last = -1;
return L;
}
插入元素
在原序列的第i位置上插入元素X
(a1,a2,…ai, …,an)——>(a1,a2,…,X,ai,…,an)
方法:
将ai~an向后移动一位
将X置于空出的第i个序列位置
修改last指针,使之指向最后一个元素
bool Insert(List L, ElementType X, int i) {
//i值a_i,位于下标为i-1的位置
//检查顺序表是否满了
if (L->Last == MAXSIZE - 1) {
printf("the list is full!\n");
return false;
}
for (position j = L->Last; j >= i-1; j--) {
L->Data[j + 1] = L->Data[j];
}
L->Data[i - 1] = X;
L->Last++;
return true;
}
查找X的位置
若找到X的位置,返回下标;
若没有找到,返回-1;
position find(List L, ElementType X) {
position i = 0;
while (i <= L->Last && L->Data[i] != X) {
i++;
}
if (i != L->Last) {
return i;
}
return -1;
}
删除第i个元素
(a1,a2,…,ai,ai+1,…,an)——>(a1,a2,…,ai+1,…,an)
从ai+1开始到an往前移动一步
last–
bool delete_ele(List L, int i) {
if (i<1 || i>L->Last + 1) {
printf("该位序不存在元素!\n");
return false;
}
//i对应下标i-1的元素
position j = i-1;
while (j < L->Last) {
L->Data[j] = L->Data[j + 1];
j++;
}
L->Last--;
return true;
}
完整代码
# include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#define MAXSIZE 10
typedef int position;
typedef int ElementType;
typedef struct LNode* PtrToLNode;
typedef PtrToLNode List;
struct LNode {
ElementType Data[MAXSIZE];
position Last;
};
List MakeEmpty() {
List L = (List)malloc(sizeof(struct LNode));
L->Last = -1;
return L;
}
bool Insert(List L, ElementType X, int i) {
//i值a_i,位于下标为i-1的位置
//检查顺序表是否满了
if (L->Last == MAXSIZE - 1) {
printf("the list is full!\n");
return false;
}
for (position j = L->Last; j >= i-1; j--) {
L->Data[j + 1] = L->Data[j];
}
L->Data[i - 1] = X;
L->Last++;
return true;
}
position find(List L, ElementType X) {
position i = 0;
while (i <= L->Last && L->Data[i] != X) {
i++;
}
if (i != L->Last) {
return i;
}
return -1;
}
bool delete_ele(List L, int i) {
if (i<1 || i>L->Last + 1) {
printf("该位序不存在元素!\n");
return false;
}
//i对应下标i-1的元素
position j = i-1;
while (j < L->Last) {
L->Data[j] = L->Data[j + 1];
j++;
}
L->Last--;
return true;
}
void print_link(List L) {
position l = L->Last;
position i = 0;
while (i<=l) {
printf("a[%d]: %d\n", i, L->Data[i]);
i++;
}
}
int main() {
List L = NULL;
L = MakeEmpty();
ElementType X;
int N;
scanf_s("%d", &N);
while (N--) {
scanf_s("%d", &X);
if (Insert(L, X, 1)==false) {
printf("insert error!\n");
}
}
print_link(L);
position exi = find(L, 5);
printf("exi : %d\n", exi);
if (delete_ele(L, 2)) {
printf("删除成功!\n");
}
print_link(L);
}