Insert code of data structure

#include<stdio.h>
#include<malloc.h> 
#include<stdlib.h>	

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 is_empty(struct Arr *pArr);	
bool is_full(struct Arr *pArr);
void show_arr(struct Arr *pArr);	//展示 

int main(){
    
    
	struct Arr arr;
	init_arr(&arr,6);
	append_arr(&arr,1);
	append_arr(&arr,2);
	append_arr(&arr,3);
	append_arr(&arr,4);
	append_arr(&arr,5);
	insert_arr(&arr,1,99) ;		
	show_arr(&arr);
	return 0;
}
bool insert_arr(struct Arr *pArr,int pos,int val){
    
    
	int i;
	if(is_full(pArr))
		return false;
	if(pos<1||pos>pArr->cnt+1)
		return false;
	for(i=pArr->cnt-1;i>=pos-1;--i){
    
    //【1】
		pArr->pBase[i+1]=pArr->pBase[i];
	}
	pArr->pBase[pos-1]=val;
	(pArr->cnt)++;//先执行前面,后执行后面的 
	return true;
} 

image.png

insert_arr(&arr,6,99) ;

image.png

insert_arr(&arr,7,99) ;

Because the length of the array is 6, it is inserted at the 7th position, which is invalid.
image.png

[1] You don’t need to remember the conditions of the for loop, you just need to simulate it yourself

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/106304240