C 语言顺序表
作者:互联网
这个顺序表是使用数组来实现的,顺序表的插入、删除、遍历等操作,下面是 c 语言的完整实现代码:
#define _CRT_SECURE_NO_WARNINGS //(放在最前面)
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
struct student {
int num;
char name[20];
int age;
int score;
};
typedef struct student student_t;
//定义一个顺序表用来存放学生信息
#define STUTBL_SIZE 100
struct stu_seq {
student_t data[STUTBL_SIZE];
int len; //保存顺序表的长度
};
typedef struct stu_seq stuseq_t;
stuseq_t stu_info; // 定义顺序表,可以存放100个学生信息
//初始化一个空表
int init_seqlist(stuseq_t *pstu_seq) {
memset(pstu_seq, 0, sizeof(stuseq_t));
return 0;
}
//顺序表的插入操作,往顺序表中插入一个元素
int insert_seqlist_from_tail(stuseq_t *pstu_seq, student_t *pstu) {
int index = 0;
if ((pstu_seq == NULL) || (pstu == NULL)) {
printf("para error\n");
return -1;
}
if (pstu_seq->len >= STUTBL_SIZE) {
printf("table is full\n");
return -1;
}
index = pstu_seq->len;
memcpy(&pstu_seq->data[index], pstu, sizeof(student_t));
pstu_seq->len++;
return 0;
}
/*
* 根据学生姓名,删除顺序表中指定的学生信息,成功返回 0 ,失败返回 -1
*/
int del_seqlist_by_name(stuseq_t *pstu_seq, char *name) {
int i = 0;
int j = 0;
for (i = 0; i < pstu_seq->len; i++) {
if (strcmp(pstu_seq->data[i].name, name) == 0) {
//成功找到了要删除的学生信息的下标,就开始执行删除操作
for (j = i; j < pstu_seq->len - 1; j++) {
memcpy(&pstu_seq->data[j], &pstu_seq->data[j + 1],
sizeof(student_t));
}
pstu_seq->len--;
return 0;
}
}
printf("can not find record\n");
return -1;
}
/*
根据学生姓名,在顺序表中查找该学生的信息,通过输出参数 *pstuinfo返回
查找成功返回 0 ,找不到,或者失败返回 -1
*/
int query_seqlist_by_name(stuseq_t *pstu_seq, char *name,
student_t *pstuinfo) {
int i = 0;
int j = 0;
for (i = 0; i < pstu_seq->len; i++) {
if (strcmp(pstu_seq->data[i].name, name) == 0) {
//成功找到了学生信息,将信息返回给输出参数
memcpy(pstuinfo, &pstu_seq->data[i], sizeof(student_t));
return 0;
}
}
printf("can not find record\n");
return -1;
}
// 遍历顺序表
void show_seqlist(stuseq_t *pstu_seq) {
int i = 0;
for (i = 0; i < pstu_seq->len; i++) {
printf("%d %s %d %d\n",
pstu_seq->data[i].num,
pstu_seq->data[i].name,
pstu_seq->data[i].age,
pstu_seq->data[i].score);
}
}
int main(int argc, char *argv[]) {
student_t stu; // 定义一个学生信息结构体类变量
char stu_name[20];
memset(stu_name, 0, 20);
init_seqlist(&stu_info); //初始化顺序表
while (1) {
memset(&stu, 0, sizeof(student_t));
printf("请分别输入学生的学号, 姓名, 年龄, 成绩(学号输入0终止输入):\n");
scanf("%d %s %d %d", &stu.num, stu.name, &stu.age, &stu.score);
if (stu.num == 0) break;
insert_seqlist_from_tail(&stu_info, &stu);
}
show_seqlist(&stu_info);
printf("input delete stu name:\n");
scanf("%s", stu_name);
del_seqlist_by_name(&stu_info, stu_name);
show_seqlist(&stu_info);
printf("input query stu name:\n");
scanf("%s", stu_name);
query_seqlist_by_name(&stu_info, stu_name, &stu);
printf("%d %s %d %d\n", stu.num, stu.name, stu.age, stu.score);
return 0;
}
标签:顺序,语言,seq,int,seqlist,stu,pstu,name 来源: https://www.cnblogs.com/huvjie/p/14932207.html