1)编写一个程序,实现顺序表的各种基本操作(假设顺序表的元素类型为学生记录,包括学号! 姓名和成绩),并在此基础上设计一个主程序完成如下功能: (2)初始化顺序表 SeqList; (3)输入顺序表的元素(5 条记录) (4)编写 PrintList 函数,输出顺序表 SeqList 所有元素; (5)编写 LocateElement 函数,查找顺序表元素的位置; (6)编写 InsertElement 函数,向顺序表中插入新元素,并调用该函数,在第 3个元素位 置上插人一条学生记录; (7)编写 DeleteElement 函数,删除顺序表元素,并调用该函数删除顺序表 SeqList 的第 1 个元素,输出删除后的线性表;
时间: 2023-05-30 19:06:18 浏览: 125
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
typedef struct {
int id;
char name[20];
int score;
} student;
typedef struct {
student data[MAXSIZE];
int length;
} SeqList;
void InitList(SeqList *L) {
L->length = 0;
}
void PrintList(SeqList L) {
int i;
printf("ID\tName\tScore\n");
for (i = 0; i < L.length; i++) {
printf("%d\t%s\t%d\n", L.data[i].id, L.data[i].name, L.data[i].score);
}
}
int LocateElement(SeqList L, int id) {
int i;
for (i = 0; i < L.length; i++) {
if (L.data[i].id == id)
return i;
}
return -1;
}
int InsertElement(SeqList *L, int pos, student s) {
int i;
if (pos < 1 || pos > L->length + 1 || L->length == MAXSIZE)
return 0;
for (i = L->length - 1; i >= pos - 1; i--) {
L->data[i + 1] = L->data[i];
}
L->data[pos - 1] = s;
L->length++;
return 1;
}
int DeleteElement(SeqList *L, int pos) {
int i;
if (pos < 1 || pos > L->length)
return 0;
for (i = pos; i < L->length; i++) {
L->data[i - 1] = L->data[i];
}
L->length--;
return 1;
}
int main() {
SeqList L;
student s;
int i, pos;
InitList(&L);
for (i = 0; i < 5; i++) {
printf("Enter student %d's id, name and score: ", i + 1);
scanf("%d%s%d", &s.id, s.name, &s.score);
InsertElement(&L, i + 1, s);
}
printf("The list is:\n");
PrintList(L);
printf("Enter the id you want to locate: ");
scanf("%d", &i);
pos = LocateElement(L, i);
if (pos == -1)
printf("Can't find the student.\n");
else
printf("The student is at position %d.\n", pos + 1);
s.id = 100;
strcpy(s.name, "Li Si");
s.score = 80;
InsertElement(&L, 3, s);
printf("After inserting a new student at position 3:\n");
PrintList(L);
DeleteElement(&L, 1);
printf("After deleting the first student:\n");
PrintList(L);
return 0;
}
阅读全文