我是靠谱客的博主 天真皮带,这篇文章主要介绍线性表的顺序表示和实现 (创建,插入,删除,查找)数据结构 严蔚敏(C语言版)代码实现,现在分享给大家,希望可以做个参考。

实现工具:dev
顺序表功能:
创建一个空的线性表;
在线性表中插入元素;
在线性表中删除元素;
在线性表中查找元素;
代码:(详解请看注释)

复制代码
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include<stdio.h> #include<stdlib.h>//动态分配需要的头文件 #define LIST_INIT_SIZE 100 #define LISTNCREAMENT 10 #define OK 1 #define FALSE 0 #define OVERFLOW 2//溢出 typedef float ElemType; typedef int Status; //线性表动态分配内存的顺序存储结构 typedef struct { ElemType *elem;//存储的基地址 int length;//当前长度 int listsize;//当前分配的最大容量 }SqList; ElemType * p,* q,e;//注意,e要定义为全局变量 ElemType * newbase;//若存储不够的话,新分配的基地址 //创建线性表 (空表) Status InitList_Sq(SqList &L) { L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));//为顺序表分配一片连续的存储空间 L.length=0;//初始化当前长度 L.listsize=LIST_INIT_SIZE;//初始化当前最大容量 return OK; } //线性表的插入 Status ListInsert_Sq(SqList &L,int i,ElemType e) { if(i<1||i>L.length+1)//注意长度+1 { return FALSE; } if(L.length>L.listsize)//若长度超过了当前最大容量,则需要新开辟空间 { //realloc的使用 newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTNCREAMENT)*sizeof(ElemType)); if(!newbase)//判断新空间是否开辟 { exit(OVERFLOW); } L.elem=newbase;//将结构体中的数据更新 L.listsize+=LISTNCREAMENT; } q=&(L.elem[i-1]);//p指向的是第i个元素 for(p=&L.elem[L.length-1];p>=q;--p) //插入时,需要从最后一个元素开始往后挪 //p指向的是数据中的最后一个元素,其中第i个元素也要进行挪位 { *(p+1)=*p; } *q=e;//将插入的元素e插入进去 ++L.length;//顺序表的长度加一 return OK; } //删除操作 ElemType ListDelete_Sq(SqList &L,int i, ElemType &e) { if(i<1||i>L.length)//注意边界 { return FALSE; } p=&L.elem[i-1];//p是要删除的第i个元素 e=*p;//将删除的元素赋值给e q=L.elem+L.length-1;//表尾元素的位置 for(++p;p<=q;++p)//将元素往前移动 { *(p-1)=*p; } --L.length;//长度减一 return e; } //查找 int LocateElem_Sq(SqList L,ElemType e) { int i; i=1; while(i<=L.length&&L.elem[i-1]!=e) { ++i; } if(i<L.length) { return i; } else return FALSE; } int main() { Status i,j; SqList La; //创建空表 InitList_Sq(La); //将表赋值为1 2 3 4 5 for(i=1;i<=5;i++) { ListInsert_Sq(La,i,i); } //输出顺序表 for(i=0;i<5;i++) { printf("%f ",La.elem[i]); } printf("n"); //在顺序表的第二个位置插入11 ListInsert_Sq(La,2,11); //输出新表 for(i=0;i<La.length;i++) { printf("%f ",La.elem[i]); } printf("n"); //删除顺序表的第4个元素 ListDelete_Sq(La,4,e); for(i=0;i<La.length;i++) { printf("%f ",La.elem[i]); } printf("n"); //查找顺序表中元素11,并返回其位置 j=LocateElem_Sq(La,11); printf("%d ",j); return 0; }

控制台输出结果:

最后

以上就是天真皮带最近收集整理的关于线性表的顺序表示和实现 (创建,插入,删除,查找)数据结构 严蔚敏(C语言版)代码实现的全部内容,更多相关线性表的顺序表示和实现内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部