C 語言順序表
阿新 • • 發佈:2021-06-25
這個順序表是使用陣列來實現的,順序表的插入、刪除、遍歷等操作,下面是 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; }