欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

顺序表的增删改查

程序员文章站 2022-03-09 08:41:06
...
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
typedef int ElemType;
typedef struct {
	int *array;//malloc的返回值为地址 
	int length;
}SqList;

int ListInit(SqList *L){
	L->array = (int*)malloc(MAXSIZE * sizeof(int));//创建数组,函数返回值为地址 
	if(L->array == 0){
		return 0;
	}
	L->length = 0;
	return 1;
} 

int ListInsert(SqList *L, int i, int e){
	int k;
	if(i < 1 || i > L->length + 1){
		return 0;
	}
	if(L->length >= MAXSIZE){
		return 0;
	}
	if(i <= L->length){
		for(k = L->length - 1; k >= i - 1; i++){
			L->array[k + 1] = L->array[k];
		}
	}
	L->array[i - 1] = e;
	L->length++;
	//printf("L->array[%d] = %d\n", i, L->array[i]);
	return 1;
}

int ListGet(SqList L, int i, int *e){
	if(i < 1 || i > L.length){
		return 0;
	}
	*e = L.array[i - 1];
	//printf("e = %d", *e);
	return 1;
}

int ListDelete(SqList *L, int i, int *e){
	int k;
	if(i < 1 || i > L->length){
		return 0;
	}else{
		*e = L->array[i - 1];
		for(k = i; k <= L->length - 1; k++){
			L->array[k - 1] = L->array[k];
		}
		L->length--;
		return 1;
	}
	
}

int main()
{
	SqList L;	
	int i;
	int e;
	//初始化链表 
	if(ListInit(&L)){
		printf("ListInit succeed!\n");
	}else{
		printf("ListInit failed!\n");
	}
	//插入一个结点 
	printf("insert num and i in the List(end of i -1) :\n");
	while(1){
		scanf("%d%d", &e, &i);
		if(i == -1){
			printf("INSERT END\n\n");
			break;
		} 	
		if(ListInsert(&L,i, e)){
			printf("ListInsert succeed!\n");
		}else{
			printf("ListInsert failed!\n");
		}		
	}
	//根据下标查找节点
	printf("请问需要获得链表中的第几个元素?");
	scanf("%d", &i); 
	if(ListGet(L, i, &e)){
		printf("ListGet succeed!\n");
		printf("第%d个链表的值为array[%d] = %d\n\n", i, i - 1, e);
	}else{
		printf("ListGet failed!\n");
	}
	//删除一个节点
	printf("请问要删除链表中的第几个元素?");
	scanf("%d", &i);
	if(ListDelete(&L, i, &e)){
		printf("ListDelete succeed!\n");
		printf("被删除的节点的值为%d", e);
	}else{
		printf("ListDelete failed!\n");
	}
	
}

顺序表的增删改查