版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/52984999
顺序表基本用法
#include <stdio.h>
#include <malloc.h>
#define max (20)
typedef struct {
char data[max];
int last;
}Sequenlist;
void Sqlsetnull(Sequenlist * ); //置空栈
Sequenlist * builtSeq(); //建空栈
int Sqllength(Sequenlist *); //计算顺序表长度
char Sqlget(Sequenlist *,int ); //获取元素
void Sqllocate(Sequenlist *, char ); //按值查找
int isFull(Sequenlist *); //判断表满
int Sqlinsert(Sequenlist * ,int i ,char ); //插入元素
int Sqldelete(Sequenlist * ,int i ); //删除元素
void show(Sequenlist *);
void Order(Sequenlist *);
int main (){
Sequenlist * l = builtSeq();
while(1){
printf("1.插入元素\t\t2.删除元素\n3.获取元素\t\t4.按值查找\n5.展示所有元素\t\t6.改变顺序\n");
char temp ,ch;
int n,m,s,key;
fflush(stdin);
scanf("%d",&key);
switch(key){
case 1:
printf("请输入需要插入的元素个数");
int i ;
fflush(stdin);
scanf("%d",&i);
printf("\n输入元素:\n");
for (int j = 0 ; j < i ; j ++){
fflush(stdin);
scanf ("%c",&temp);
Sqlinsert(l,j,temp);
}
break;
case 2:
printf("\n请输入要删除的元素的下标: ");
scanf("%d",&n);
putchar('\n');
Sqldelete(l,n);
break;
case 3:
printf("请输入下标: ");
scanf("%d",&m);
ch = Sqlget(l,m);
printf("%c",ch);
break;
case 4:
fflush(stdin);
scanf ("%c",&s);
Sqllocate(l,s);
break;
case 5:
show(l);
break;
case 6:
Order(l);
break;
}
}
}
void Sqlsetnull(Sequenlist * l){
l-> last= -1;
}
Sequenlist * builtSeq(){
Sequenlist * l ;
l = (Sequenlist * )malloc (sizeof(Sequenlist));
Sqlsetnull(l);
return l;
}
int Sqllength(Sequenlist * l){
return l->last;
}
int isFull(Sequenlist * l){
if ((l->last)+1>=max)
return 1;
return 0;
}
int Sqlinsert(Sequenlist * l ,int i ,char x){ //i表示下标,last表示最后一个元素的下标
int j ;
if(isFull(l)){
printf("\n表已满 !!\n");
return 0;
}
else if ((i < 0)||(i>l->last+2)){
printf("\n操作错误!\n");
return 0;
}
else {
for ( j = l->last;j>=i;j--){
l->data[j+1] = l->data[j];
}
l->data[i] = x;
l->last++;
return 1;
}
}
int Sqldelete(Sequenlist * l ,int i ){
int j;
if (l->last<0){
printf("\n表为空 !!\n");
return 0;
}
else if ((i<1)||(i>l->last+1)){
printf("\n参数错误 !!\n");
return 0;
}
for(j = i ; j <= l->last;j++){
l->data[j-1] = l->data[j];
}
l->last--;
return 1;
}
char Sqlget(Sequenlist * l,int i){
char x ;
if (i < 1||i>Sqllength(l)){
printf("\n超出范围 !!\n");
}
else {
x = l->data[i-1];
printf("该值为:%c\n",x);
}
return x;
}
void show (Sequenlist * l){
for (int i= 0 ; i<= l->last;++i){
printf("%c ",l->data[i]);
}
printf("\n");
}
void Order(Sequenlist *l){
char temp ;
int n = l->last - 1;
for (int i = 0;i<=n-i;++i){
temp = l->data[i];
l->data[i]=l->data[n-i];
l->data[n-i]= temp;
}
}
void Sqllocate(Sequenlist * l ,char x ){
int i ,z = 0;
for (int i = 0; i < l->last;i++){
if (l->data[i]==x){
printf("\n第%d位\n",i+1);
z=1;
}
}
if (z == 0){
printf("\n没有找到!\n");
}
}