C语言实现顺序表
main.c
#include "test.h"
void test();
ElementType dataArray[] = {
{1,"侠客行"},
{2,"将进酒"},
{3,"神来之笔"},
{4,"青莲剑歌"}
};
int main()
{
test();
return 0;
}
void test(){
SeqList seqList;
InitList(&seqList,dataArray,4);
PrintList(&seqList);
}
test.c
#include "test.h"
void InitList(SeqList * seqList,ElementType * elemArray,int length){
if (length > MAX_SIZE){
printf("超出数组最大容量。");
}
seqList->length = 0;
for (int i=0;i<length;i++){
InserElement(seqList,i,elemArray[i]);
}
}
void InserElement(SeqList * seqList,int index,ElementType element){
if (seqList->length + 1 >= MAX_SIZE){
printf("数组已满。");
return;
}
if (index < 0 || index > MAX_SIZE-1){
printf("输入下标不合法。");
return;
}
if (index > seqList->length){
printf("输入下标超过数组长度。");
return;
}
for (int i=seqList->length-1;i>=index;i--){
seqList->data[i+1] = seqList->data[i];
}
seqList->data[index] = element;
seqList->length++;
}
void PrintList(SeqList * seqList){
for (int i=0;i<seqList->length;i++){
printf("%d\t%s.\n",seqList->data[i].id,seqList->data[i].name);
}
}
test.h
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 255
typedef struct {
int id;
char * name;
}ElementType;
typedef struct {
ElementType data[MAX_SIZE];
int length;
}SeqList;
void InitList(SeqList * seqList,ElementType * elemArray,int length);
void InserElement(SeqList * seqList,int index,ElementType element);
void PrintList(SeqList * seqList);
#endif
|