【计蒜课】【数据结构】【顺序表查找、删除、遍历操作的复习答案】
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
typedef struct Vector {
int size,length;
int *data;
} Vector;
void init(Vector *vector,int size) {
vector->size=size;
vector->length=0;
vector->data=(int*)malloc(sizeof(int)*size);
}
void expand(Vector *vector) {
int *old_data=vector->data;
vector->size=vector->size*2;
vector->data=(int*)malloc(sizeof(int)*vector->size);
for(int i=0;i<vector->length;i++){
vector->data[i]=old_data[i];
}
free(old_data);
}
int insert(Vector *vector, int loc, int value) {
if (loc < 0 || loc > vector->length) {
printf("failed\n");
return ERROR;
}
if (vector->length >= vector->size) {
//return ERROR;
expand(vector);
}
for (int i = vector->length; i > loc; --i) {
vector->data[i] = vector->data[i - 1];
}
vector->data[loc] = value;
vector->length++;
printf("success\n");
return OK;
}
int search(Vector *vector,int value) {
for(int i=0;i<vector->length;i++){
if(vector->data[i] == value){
printf("success\n");
return OK;
}
}
printf("failed\n");
return ERROR;
}
int delete_node(Vector *vector,int index) {
if(index<0 || index >= vector->length){
printf("failed\n");
return ERROR;
}
for(int i=index+1;i<vector->length;i++){
vector->data[i-1]=vector->data[i];
}
vector->length--;
printf("success\n");
return OK;
}
void print(Vector *vector) {
for(int i=0;i<vector->length;i++){
if(i>0){
printf(" ");
}
printf("%d",vector->data[i]);
}
printf("\n");
}
void clear(Vector *vector) {
free(vector->data);
free(vector);
}
int main() {
Vector *a = (Vector *)malloc(sizeof(Vector));
init(a, 20);
int m;
int t;
int x,y;
scanf("%d",&m);
while(m>=1 && m<=100){
scanf("%d",&t);
if(t == 4){
print(a);
}
if(t == 1){
scanf("%d %d",&x,&y);
insert(a,x,y);
}
if(t == 2){
scanf("%d",&x);
delete_node(a,x);
}
if(t == 3){
scanf("%d",&x);
search(a,x);
}
m--;
}
clear(a);
return 0;
}