数据结构——顺序表基本操作(C语言)
1.初始化2.创建3.插入4.删除5.按值查找6.打印
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10010
#define ElemType int
typedef struct {
ElemType data
[MAXSIZE
];
int length
;
}SeqList
;
bool
InitList(SeqList
*l
){
l
->length
=0;
return true
;
}
bool
CreateList(SeqList
*l
,ElemType x
){
if(l
->length
> MAXSIZE
)
return false
;
l
->data
[l
->length
++]=x
;
return true
;
}
bool
ListInsert(SeqList
*l
,int index
,ElemType e
){
if(index
> l
->length
||index
<0||(l
->length
+1)>MAXSIZE
){
return false
;
}
for(int i
= l
->length
-1; i
>=index
;i
--){
l
->data
[i
+1]=l
->data
[i
];
}
l
->data
[index
]=e
;
l
->length
++;
return true
;
}
bool
DeleteList(SeqList
*l
,int index
,ElemType
&e
){
if(index
> l
->length
-1||index
<0){
return false
;
}
e
=l
->data
[index
];
for(int i
=index
;i
< l
->length
-1;i
++){
l
->data
[i
]=l
->data
[i
+1];
}
l
->length
--;
}
bool
findElemByValue(SeqList
*l
,ElemType e
,int &index
){
int i
;
for(i
=0;(i
< l
->length
)&& (e
!=l
->data
[i
]);i
++);
if(i
== l
->length
)
return false
;
else{
index
= i
;
return true
;
}
}
void Check(bool flag
,int value
){
if(flag
==true
){
printf("操作成功!\n");
if(value
!=NULL)
printf("操作结果返回值为:%d\n",value
);
}else{
printf("操作失败!\n");
}
}
void PrintList(SeqList
*l
){
for(int i
=0;i
< l
->length
;i
++){
printf("%d ",l
->data
[i
]);
}
printf("\n");
}
int main(){
int n
;
printf("输入元素个数:");
scanf("%d",&n
);
SeqList list1
;
printf("初始化顺序表");
bool flag
=InitList(&list1
);
if(flag
== true
){
printf("初始化完成!\n");
}else{
printf("初始化失败!\n");
}
printf("开始存储元素\n");
while(n
--){
printf("输入元素:");
int elem
;
scanf("%d",&elem
);
bool flagC
=CreateList(&list1
,elem
);
if(flagC
== false
){
printf("创建失败!\n");
return 0;
}
}
printf("欢迎使用顺序表");
while(1){
printf("\n请选择操作\n1.插入\n2.删除\n3.按值查找\n4.打印所有元素\n");
int op
;
int index
,e
;
bool flag
;
scanf("%d",&op
);
switch(op
%10){
case 1:
printf("输入插入位置(下标)与插入元素:\n");
scanf("%d %d",&index
,&e
);
flag
=ListInsert(&list1
,index
, e
);
Check(flag
,e
);
break;
case 2:
printf("输入删除位置(下标):\n");
scanf("%d",&index
);
flag
=DeleteList(&list1
,index
,e
);
Check(flag
,e
);
break;
case 3:
printf("输入查找元素的值:\n");
scanf("%d",&e
);
flag
=findElemByValue(&list1
,e
,index
);
Check(flag
,index
);
break;
case 4:
PrintList(&list1
);
break;
default:
printf("error\n");
break;
}
}
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-1109.html