您的位置:首页 > 编程语言 > C语言/C++

顺序表的C++实现

2015-04-16 17:36 190 查看
学习了一下顺序表,用C++实现了一下算法,有错误敬请指正

/*
1.顺序表的初始化
2.在顺序表最后插入元素
3.在顺序表中插入元素
4.删除表中元素
5.按序号查找表中元素
6.查找关键字所在节点
7.输出所有节点
*/
#include<stdio.h>
#include<string.h>
#include<iostream>
#define MAXLINE 10  //定义顺序表最大长度
typedef struct
{
char name[20] ;
char key[10];
int age;
}DATA;
typedef struct//定义顺序表结构
{
DATA ListData[MAXLINE + 1];//保存顺序表
int ListLen;//顺序表已存节点数
}SLType;
void SLInit(SLType* SL)//初始化顺序表
{
(*SL).ListLen= 0;//顺序表初始为空
}
int SLInsert(SLType* SL, int n, DATA data)  //插入新元素
{
int i;
if ((*SL).ListLen>=MAXLINE)  //如果表长度大于最大值
{
std::cout << "顺序表已满,不能插入新节点!!\n";
return 0;
}
if (n<1 || n>(*SL).ListLen - 1) //插入节点错误
{
std::cout << "插入序号错误,不能插入节点\n";
return 0;
}
for (i = (*SL).ListLen; i >= n; i--)//将表中数据向后移一位
{
(*SL).ListData[i + 1] = (*SL).ListData[i];  //从最后向n节点移动
}
(*SL).ListData
= data;//插入数据
(*SL).ListLen++;//表长增加1
return 1;//成功插入,返回1
}
int SLAdd(SLType* SL, DATA data)  //在表末插入新数据
{
if ((*SL).ListLen >= MAXLINE)  //如果表长度大于最大值
{
std::cout << "顺序表已满,不能插入新节点!!\n";
return 0;
}
else
{
(*SL).ListData[(*SL).ListLen++] = data; //在表末插入新数据
(*SL).ListLen++;//表长增加1
return 1;
}
}
int SLDelete(SLType *SL, int n)//删除表中元素
{
if (n < 1 || n>(*SL).ListLen + 1)
{
std::cout << "删除节点错误,不能删除节点\n";
}
for (int i = n; i < (*SL).ListLen; i++)
{
(*SL).ListData[i] = (*SL).ListData[i + 1];//将顺序表数据前移
}
(*SL).ListLen--;
return 1;
}
DATA *SLFindData(SLType* SL, int n)//查找序号对应元素
{
if (n<1 || n>(*SL).ListLen + 1)
{
std::cout << "查找节点错误,无法找到需要元素\n";
return 0;
}
else
{
return &(*SL).ListData
;
}
}
int SLFindByCont(SLType* SL, char *key)//查找关键字所在节点
{
for (int i = 0; i <= (*SL).ListLen; i++)
{
if (strcmp((*SL).ListData[i].key, key) == 0)//字符比较
{
return i;//返回对应所在节点
}
else
return 0;
}
}
int SLAll(SLType* SL)//输出所有节点
{
for (int i = 0; i <= (*SL).ListLen; i++)
{
std::cout << "Name: " << (*SL).ListData[i].name  << "  Key: " << (*SL).ListData[i].key << "  Age: " << (*SL).ListData[i].age << "\n";

}
return 0;
}
void main()
{
int i;
SLType SL = { 0 };//定义顺序表
DATA data = {0};//定义节点保存变量
DATA* pdata;//定义节点保存指针变量
char key[10] = {0};//保存关键字
SLInit(&SL); //初始化顺序表
std::cout << "初始化顺序表!";
std::cout << "输入添加的节点(学号 姓名 年龄)\n";
while (1)
{
fflush(stdin);//清空输入缓冲期
std::cin >> data.key >> data.name >> data.age;
if (data.age != 0)
{
if (!SLAdd(&SL, data))
{
break;
}
}
else
break;
}
std::cout << "顺序表中节点为:\n";
SLAll(&SL);//显示所有节点
fflush(stdin);
std::cout << "取出节点号为";
std::cin >> i;
pdata=SLFindData(&SL, i);//按序号查找结点
if (pdata)
{
std::cout << "第" << i << "个节点为:" << (*pdata).key << (*pdata).name << (*pdata).age << "\n";
}
fflush(stdin);
std::cout << "查找关键字!";
std::cin >> key;
i = SLFindByCont(&SL, key);//按关键字查找结点
pdata = SLFindData(&SL, i);//输出节点详细内容
if (pdata)
{
std::cout << "节点详细数据为:" << (*pdata).key << (*pdata).name << (*pdata).age << "\n";
}
getchar();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: