数据结构---顺序表实验(C语言实现)

实验目的

1.掌握线性表的基本原理; 2.掌握顺序表的存储结构; 3.掌握顺序表的创建、查找、插入、删除的实现方法;

实验内容

问题描述

在给出一组初始数据的情况下,实现顺序表的定义、创建、查找、插入、删除。

算法

顺序表的定义:一维数组、最大长度、实际长度 顺序表的创建:初始化顺序表 顺序表的查找:给出位置 i 的数据 顺序表的插入:位置 i 和后面的数据全部后移一位;在指定的位置 i 插入一个数据;表长加 1 顺序表的删除:位置 i 后面的数据全部前移一位,覆盖掉位置 i 的数据;表长减 1

实验代码示例

#include<stdio.h>
#define MAXSIZE 20   //最大表长 

//定义一个顺序表 
typedef struct{
          
   
	int data[MAXSIZE];    //用于存储数据的一维数组 
	int ListLen;          //线性表当前实际长度 
}SeqList; 

//用于遍历当前顺序表的元素 
void DisplayList(SeqList* L){
          
   
	int i;
	for(i = 0;i < L->ListLen;i++){
          
   
		printf("%d ",L->data[i]);
	}
	printf("
"); 
}

//顺序表的查找(给出指定位置 i (非数组下标)的元素数据)
int GetElem(SeqList* L,int i){
          
    
	//先判断需要查询的指定位置是否合法(指定位置超出范围或顺序表为空表均报错,返回-1)
	if(i <= 0 || i > L->ListLen || L->ListLen == 0){
          
     
		return -1;  
	}
	return L->data[i - 1];   //返回指定位置上的元素
} 

//顺序表的插入(将新元素 e 插入到指定位置 i 上)
int  ListInsert(SeqList* L,int i,int e){
          
   
	int j;
	//如果指定位置超出范围或者当前表长已是最大长度,则报错,返回-2 
	if(i <= 0 || i > L->ListLen + 1 || L->ListLen == MAXSIZE){
          
   
		return -2;
	}
	//从后往前,将前一位数组元素赋给后一位数组 
	for(j = L->ListLen - 1;j >= i - 1;j--){
          
   
		L->data[j + 1] = L->data[j];
	}
	L->data[i - 1] = e;   //将新元素 e 存入指定位置 
	L->ListLen++;         //插入元素后表长 +1 
	return 0;
}

//顺序表的删除(将指定位置 i 上的元素删除)
int ListDelete(SeqList* L,int i){
          
   
	int j;
	//如果指定位置超出范围或者顺序表为空表,则报错,返回-3 
	if(i <= 0 || i > L->ListLen || L->ListLen == 0){
          
   
		return -3;
	}
	//从前往后,将后一位数组元素赋给前一位 
	for(j = i - 1;j < L->ListLen;j++){
          
   
		L->data[j] = L->data[j + 1];
	}
	L->ListLen--;        //删除元素后表长 -1 
	return 0;
} 

int main(){
          
   
	int Error = 0;   //-1:查找出错  -2:插入出错  -3:删除出错 
	SeqList seqlist;   //定义一个顺序表
	seqlist.ListLen = 0; //先将顺序表当前表长设置为 0  
	int length,i,index,element; 
	
	printf("Please enter the length of the list:");   //读取需要存放的元素个数 
	scanf("%d",&length);
	
	//将输入的关键字依次放入顺序表中 (顺序表赋值) 
	seqlist.ListLen = length;   //将当前表长设置为需要存放的元素个数 
	printf("Please enter the data:");
	for(i = 0;i < seqlist.ListLen;i++){
          
   
		scanf("%d",&(seqlist.data[i]));   
	}
	DisplayList(&seqlist);    //遍历一次表 
	
	//查找指定位置上的元素 
	printf("Please enter the index of the element which you want to search:");
	scanf("%d",&index);
	printf("The target element is: %d
",GetElem(&seqlist,index));
	
	//顺序表的插入 
	printf("Plese enter the index and its element which you want to insert:");
	scanf("%d %d",&index,&element);
	printf("Error: %d
",ListInsert(&seqlist,index,element));
	DisplayList(&seqlist);    //遍历一次表 
	  
	//顺序表的删除
	printf("Plese enter the index which you want to delete:"); 
	scanf("%d",&index);
	printf("Error: %d
",ListDelete(&seqlist,index));
	DisplayList(&seqlist);    //遍历一次表 
		
	return 0;
}

程序运行示例

输入无错误信息的情况:

人为制造错误信息的情况:

程序返回ERROR分别为-1、-2、-3,相应取值对应的情况见代码注释

经验分享 程序员 微信小程序 职场和发展