The delete operation code of the data structure

#include<stdio.h>
#include<malloc.h> 		//包含了malloc函数 
#include<stdlib.h>		//包含了exit函数 

struct Arr 
{
    
    
	int *pBase;	//存储数组第一个元素的地址 
	int len;	//数组所能容纳的最大元素的个数 
	int cnt;	//当前数组有效元素个数 
};

void init_arr(struct Arr *pArr,int length);	//初始化数组 
bool append_arr(struct Arr *pArr,int val);	//追加 
bool insert_arr(struct Arr *pArr,int pos,int val);//表示下标为0的为第一个 元素,pos值从1开始,pos=4,表示在第4个元素前面插入一个值 
bool delete_arr(struct Arr *pArr,int pos,int *pVal);
int get();	//获取元素值 
bool is_empty(struct Arr *pArr);	
bool is_full(struct Arr *pArr);
void sort_arr();	//排序 
void show_arr(struct Arr *pArr);	//展示 
void inversion_arr(); //倒置 

int main(){
    
    
	struct Arr arr;
	int val;
	init_arr(&arr,6);
	append_arr(&arr,1);
	append_arr(&arr,2);
	append_arr(&arr,3);
	append_arr(&arr,4);
	append_arr(&arr,5);
	show_arr(&arr);

	if(delete_arr(&arr,5,&val)){
    
    //【1】
		printf("删除元素成功!\n");
		printf("您删除的元素是:%d\n",val); 
	}else{
    
    
		printf("删除失败!\n");
	}
	
	show_arr(&arr);
	return 0;
}
//删除元素并返回删除元素的值
bool delete_arr(struct Arr *pArr,int pos,int *pVal){
    
    
	int i;
	if(is_empty(pArr))
		return false;
	if(pos<1||pos>pArr->cnt)
		return false;
	//把val的地址赋给pval,*pval就是主函数的val 
	*pVal=pArr->pBase[pos-1];
	for(i=pos;i<pArr->cnt;++i)
	{
    
    
		pArr->pBase[i-1]=pArr->pBase[i]; 
	} 
	pArr->cnt--;
	return true;
}

image.png

delete_arr(&arr,7,&val)

image.png

[1] Send the address of val to pVal, then the value of val can be modified by pVal in delete. We only need to assign the value of the element to be deleted to the variable pointed to by pVal. This modifies the value of the main function, that is, modifies the value of val through the formal parameter pval, and then outputs val.

This article only shows part of the key code, detailed code, please refer to the previous article.
Reference link: https://www.bilibili.com/video/BV11s41167h6?p=13

Guess you like

Origin blog.csdn.net/dd_Mr/article/details/106305192