c语言顺序表的基本操作——插入、删除、查找、取最值

大三狗比较菜,以上代码在我的机子能运行,不保证完全正确...如有错误,欢迎指正!!!

插入操作:

#include 
#define maxSize 100

typedef struct seqlist {
	int data[maxSize];
	int length;

}seqlist;

int insertElem(seqlist *s, int p, int e) {	
	if (p<0 || p>s->length) {	//此处 s->length 等价于 (*s).length
		return 0;
	}
	for (int i = s->length-1; i >= p; i--) {
		s->data[i + 1] = s->data[i];
	}
	(*s).data[p] = e;
	++s->length;
	return 1;

}

int main() {
	int p = 2, e = 10010;
	seqlist s;
	s.length = 5;
	s.data[0] = 0;
	s.data[1] = 1;
	s.data[2] = 2;
	s.data[3] = 3;
	s.data[4] = 4;

	int flag = insertElem(&s, p, e);
	if (!flag)
		printf("fault!!!\n");
	for (int i = 0; i < s.length; i++)
		printf("a[%d]=%d\n", i, s.data[i]);


}

删除、查找操作:

#include 
#define maxsize 100
struct sqlist {
	int a[maxsize];
	int length;
};
int  delete(struct sqlist* s, int p) {
	int i;
	if (p<0 || p>(*s).length)
		return 0;
	for (i = p; i <= s->length - 1; i++) {
		s->a[i] = s->a[i + 1];
	}
	--s->length;
	return 1;
}

int search(struct sqlist s, int e) {
	int i;
	for (i = 0; i < s.length; i++) {
		if (s.a[i] == e)
			return i;
		else return -1;    //注意return语句的位置
	}
	
}

int main() {
	int i;
	struct sqlist s;
	s.length = 5;
	s.a[0] = 0; s.a[1] = 1;
	s.a[2] = 2; s.a[3] = 3; s.a[4] = 4;
	//delete(&s,0);

	int p = search(s, 4);
	printf("%d\n", p);
	return 0;
}

去最值(最大值):

int findMax(seqlist* s) {
	int index = 0, max = s->data[0];
	for (int i = 0; i < s->length; i++) {
		if (max < s->data[i]) {
			index = i;
			max = s->data[i];
		}
	}
	return max;
}

 

你可能感兴趣的:(数据结构,c语言,数据结构,顺序表)