用C语言分别尝试采用顺序表和单链表两种不同的存储结构实现由键盘输入学生信息(包括学号和成绩),学号为0作为结束标志。对建成的线性表,再分别采用正确的程序控制方法,输出线性表里储存的信息。
时间: 2023-05-30 20:04:15 浏览: 105
C语言从入门到实战-通过使用C语言来实现线性表的顺序存储
顺序表实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int num;
int score;
} Student;
typedef struct {
Student data[MAXSIZE];
int length;
} SqList;
void initList(SqList *L) {
L->length = 0;
}
void insert(SqList *L, int i, Student x) {
if (L->length == MAXSIZE) {
printf("List is full.\n");
return;
}
if (i < 1 || i > L->length + 1) {
printf("Invalid index.\n");
return;
}
for (int j = L->length; j >= i; j--) {
L->data[j] = L->data[j - 1];
}
L->data[i - 1] = x;
L->length++;
}
void printList(SqList L) {
printf("Num\tScore\n");
for (int i = 0; i < L.length; i++) {
printf("%d\t%d\n", L.data[i].num, L.data[i].score);
}
}
int main() {
SqList L;
initList(&L);
Student s;
printf("Enter student info (num score): ");
scanf("%d %d", &s.num, &s.score);
while (s.num != 0) {
insert(&L, L.length + 1, s);
printf("Enter student info (num score): ");
scanf("%d %d", &s.num, &s.score);
}
printList(L);
return 0;
}
```
单链表实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int num;
int score;
struct Node *next;
} Node;
void initList(Node **L) {
*L = NULL;
}
void insert(Node **L, int i, int num, int score) {
if (i < 1) {
printf("Invalid index.\n");
return;
}
Node *p = *L;
Node *prev = NULL;
int j = 1;
while (p && j < i) {
prev = p;
p = p->next;
j++;
}
if (i > j + 1) {
printf("Invalid index.\n");
return;
}
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->num = num;
newNode->score = score;
if (prev) {
prev->next = newNode;
} else {
*L = newNode;
}
newNode->next = p;
}
void printList(Node *L) {
printf("Num\tScore\n");
while (L) {
printf("%d\t%d\n", L->num, L->score);
L = L->next;
}
}
void destroyList(Node **L) {
while (*L) {
Node *p = *L;
*L = (*L)->next;
free(p);
}
}
int main() {
Node *L;
initList(&L);
int num, score;
printf("Enter student info (num score): ");
scanf("%d %d", &num, &score);
while (num != 0) {
insert(&L, 0, num, score);
printf("Enter student info (num score): ");
scanf("%d %d", &num, &score);
}
printList(L);
destroyList(&L);
return 0;
}
```
阅读全文