C语言 实现顺序表

线性表分为两种形式

  1. 顺序线性表

  2. 链式线性表


因为数组也是采取顺序存储形式,所以可以用数组模拟一个顺序表、

如果使用VS,请关闭安全检查,因为使用scanf 函数的时候VS会推荐你使用scanf_s,且报错的话直接跳到input.c文件中

#include "stdafx.h"
#include "stdlib.h"
#include "string.h"
#define MAXSIZE 100   //定义顺序表的最大长度
typedef struct{
	char key[15];
	char name[20];
	int age;
}DATA;

typedef struct{
	DATA ListData[MAXSIZE + 1];
	int ListLen;

}SeqListType;


void SeqListInit(SeqListType * SL){			//初始化顺序表
	SL->ListLen = 0;
}
int  SeqListLength(SeqListType * SL){		//返回顺序表的元素数量
	return (SL->ListLen);//
}
int SeqListAdd(SeqListType *SL, DATA data){			//	向顺序表中添加节点
	if (SL->ListLen >= MAXSIZE){
		printf("顺序表已满,不能在添加节点了");
		return 0;
	}
	SL->ListData[++SL->ListLen] = data;
	return 1;
}

int SeqListInsert(SeqListType *SL, int n, DATA data){
	int i;
	if (SL->ListLen >= MAXSIZE){						//插入节点
		printf("顺序表已满,不能插入元素");
		return 0;
	}
	if (n<1 || n>SL->ListLen - 1){
		printf("插入节点序号错误,不能插入元素");
		return 0;
	}
	for (i = SL->ListLen; i >= n; i++){
		SL->ListData[i++] = SL->ListData[i];
		SL->ListData[n] = data;
		SL->ListLen++;
		return 1;
	}

}
int SeqListDelete(SeqListType *SL, int n){
	int i;
	if (n<1 || n>SL->ListLen + 1){
		printf("插入节点序号错误,不能删除元素");		//	删除节点
		return 0;
	}
	for (i = n; i < SL->ListLen; i++){
		SL->ListData[i] = SL->ListData[i + 1];
		SL->ListLen--;
		return 1;
	}
}
DATA  *SeqListFindByNum(SeqListType *SL, int n){		//	按照序号查找节点
	if (n<1 || n>SL->ListLen + 1){
		printf("节点序号错误");
		return NULL;
	}
	return &(SL->ListData[n]);
}
//按关键字查找节点
int SeqListFindByCont(SeqListType *SL, char *key){
	int i;
	for (int i = 1; i <= SL->ListLen; i++){
		if (strcmp(SL->ListData[i].key, key) == 0){
			return i;
		}
		return 0;
	}
}
//遍历顺序表中所有的节点
void SeqListAll(SeqListType *SL){
	int i;
	for (i = 1; i <= SL->ListLen;i++){
		printf("%s%s%d\n", SL->ListData[i].key, SL->ListData[i].name, SL->ListData[i].age);
	}

}

int main(){
	int i;
	SeqListType SL;
	DATA data, *data1;
	char key[15];
	SeqListInit(&SL);

	do{
		printf("输入添加的节点(学号, 姓名,年龄)");
		fflush(stdin);
		scanf("%s%s%d", &data.key, &data.name, &data.age);
		if (data.age){
			if (!SeqListAdd(&SL, data))
				break;
		}
		else{
			break;
		}
	} while (1);
	printf("顺序表的节点顺序为\n");   //"\n"表示换行
	SeqListAll(&SL);
	fflush(stdin);
	printf("要取出节点的序号的关键字\n");
	scanf("%s", key);
	i = SeqListFindByCont(&SL, key);
	data1 = SeqListFindByNum(&SL, i);

	if (data1){
		printf("第%d的节点为(%s,%s,%d)",i,data1->key,data1->name,data1->age);
		//getch();
	}
	
	system("PAUSE");
	return 0;
}


你可能感兴趣的:(C语言,线性表)