前言

线性表有一种物理结构叫顺序存储结构。它由一系列连续的存储单元组成,从而使得逻辑上相邻的两个元素也连续。

  • 这样的结构可以使用一维数组来实现。数组的下标从0开始,但我们的元素是从1开始。所以,我们可以这样看:元素均对应,但标志不一样(只需在用[]时,-1即可)
1
2
3
4
5
#define MaxSize 50  // 定义线性表的最大长度
typedef struct{
ElemType data [MaxSize] ; // 表的元素
int length; // 线性表的当前长度
}SqList; // 表的类型定义

注意线性表长度和数组长度不同


操作

Insert

  1. 如果线性表长度等于数组长度,退出
  2. 如果插入到线性表长度+1以外,退出
  3. 如果不是插到最后(length + 1),那么for,从最后一个元素到第i个,一个个往后退

Delete

  1. 如果线性表为空,退出
  2. 如果删除表以外的数据,退出
  3. 如果不是删除最后位置,for,从i+1到length一个个向前移

示例

1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define TSIZE      45    /* size of array to hold title  */
#define MAXSIZE 100
struct film
{
char title[TSIZE];
int rating;
};

/* general type definitions */

typedef struct film Item;

typedef struct list
{
Item entries[MAXSIZE];//内含项的数组,**这时字符数组已经分配空间,赋值要用strcpy()**
int items; //list中的一共的项数
} List;
2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAKESIZE 20
typedef int Elememnt;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node
{
Elememnt e[MAKESIZE];
int length; //线性表长度
};

void InitList(List L)
{
L->length = 0;
}

bool ListEmpty(List L)
{
if(L->length == 0)
return true;
else
return false;
}

void ClearList(List L)
{
L->length = 0;
}

int ListLength(List L)
{
return L->length;
}

Elememnt GetElement(List L, int i)
{
return L->e[i - 1];
}

int LocateElement(int x, List L)
{
if(L->length == 0)
return 0;
for(int i = 0; i < L->length; i++)
{
if(x == L->e[i])
return i + 1;
}
return 0;
}

int Insert(List L,int i,Elememnt e)
{
int k;
if (L->length == MAKESIZE) /* 顺序线性表已经满 */
return 0;
if (i<1 || i > L->length + 1)/* 当i比第一位置小或者比最后一位置后一位置还要大时 */
return 0;
if(i < L->length)//若插入的元素不在末尾
for(k=L->length-1;k>=i-1;k--) /* 将要插入位置之后的数据元素向后移动一位 */
L->e[k+1]=L->e[k];
L->e[i-1]=e; /* 将新元素插入 */
L->length++;

return 1;
}

int DeElement(List L, int i)
{
if(L->length == 0)
return 0;
if(i < 1 || i > L->length)
return 0;
for(int j = i; j < L->length; j++)
L->e[j - 1] = L->e[j];
L->length--;
return 1;
}

void PrintList(List L)
{
for(int i = 0; i < L->length; i++)
printf("%d ", L->e[i]);
}

int main()
{
List L;
InitList(L);
for(int i = 0; i < 10; i++)
{
Insert(L , i + 1, i);
}
DeElement(L, 2);
PrintList(L);
}