数据结构-顺序表

数据结构:顺序表

顺序表是在计算机内存中以数组的形式保存的线性表,线性表的顺序存储是指用一组地址连续的存储单元依次存储线性表中的各个元素、使得线性表中在逻辑结构上相邻的数据元素存储在相邻的物理存储单元中,即通过数据元素物理存储的相邻关系来反映数据元素之间逻辑上的相邻关系,采用顺序存储结构的线性表通常称为顺序表。

顺序表

顺序表的创建

1
2
3
4
5
6
7
#define LIST_MAX_SIZE  20

typedef struct list
{
int number[LIST_MAX_SIZE];
int length;
}List;

number数组里面存放数据,length是当前顺序表的长度

顺序表的初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
List *list_init(int n)
{
int i;
List *temp = (List*)malloc(sizeof(List));
temp->length = 0;
if(n < 1)
{
return temp;
}

if (n > LIST_MAX_SIZE)
{
n = LIST_MAX_SIZE;
}


for (i = 0; i < n; i++)
{
temp->length++;
scanf("%d",&temp->number[i]);
}
return temp;
}

顺序表比较简单,判断合法性后依次输入就可以了

增加节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void add_node(List *lt)
{
if (lt == NULL)
{
printf("list is empty~\n");
return;
}
if (lt->length == LIST_MAX_SIZE)
{
printf("list is full");
return;
}

scanf("%d",&lt->number[lt->length]);
lt->length++;
}

增加节点直接增加到末尾,如果中间或在头部插入,后面的数据都要移动,我在这里没有实现这一功能。

删除节点

1
2
3
4
5
6
7
8
9
void del_node(List *lt)
{
if (lt == NULL)
{
printf("list is empty~\n");
return;
}
lt->length--;
}

这里也只实现了删除末尾节点。

修改节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void modify_num(List *lt,int n)
{
if (lt == NULL || lt->length == 0)
{
printf("list is empty~\n");
return;
}
if (n > lt->length)
{
printf("n is error!\n");
}

scanf("%d",&lt->number[n-1]);
return;
}

遍历找到要修改的节点进行修改

输出节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void printf_list(List *lt)
{
int i;
if(lt == NULL || lt->length == 0)
{
printf("list is empty!\n");
}

for (i = 0; i < lt->length; i++)
{
printf("%d\n",lt->number[i]);
}

}

遍历输出即可


数据结构-顺序表
https://carl-5535.github.io/2020/11/23/数据结构/数据结构-顺序表/
作者
Carl Chen
发布于
2020年11月23日
许可协议