顺序表
1. 静态分配
#include <iostream>
#include <string.h>
using namespace std;
#define MaxSize 100
typedef struct
{
string name;
int age;
string sex;
} student;
typedef struct
{
student data[MaxSize];
int length;
} list;
void initList(list &l)
{
l.length = 0;
}
bool listInsert(list &l, int i, student stu)
{
if (i > l.length + 1 || i <= 0)
{
return false;
}
for (int j = l.length; j >= i; j--)
{
l.data[j] = l.data[j - 1];
}
l.data[i - 1] = stu;
l.length++;
return true;
}
void findElem(list l, int i)
{
if (i > l.length || i <= 0)
{
cout << "没有找到!" << endl;
}
else
{
cout << "姓名:" << l.data[i - 1].name << endl;
cout << "性别:" << l.data[i - 1].sex << endl;
cout << "年龄:" << l.data[i - 1].age << endl;
}
}
void findall(list l)
{
if (l.length == 0)
{
cout << "顺序表为空!" << endl;
return;
}
for (int j = 0; j < l.length; j++)
{
cout << "当前位序:" << j << endl;
cout << "姓名:" << l.data[j].name << endl;
cout << "性别:" << l.data[j].sex << endl;
cout << "年龄:" << l.data[j].age << endl;
}
}
void deleteElem(list &l, int num)
{
if (num > l.length || num <= 0)
{
cout<<"输入位置错误!"<<endl;
return;
}
for (num; num < l.length; num++)
{
l.data[num - 1] = l.data[num];
}
l.length--;
cout << "删除成功!" << endl;
}
int main()
{
student stu;
int num;
list L;
initList(L);
int num1;
int num2;
int choose;
while (1)
{
cout << "1.按位置插入" << endl;
cout << "2.查询全部" << endl;
cout << "3.按位置查询" << endl;
cout << "4.按位置删除" << endl;
cout << "请选择:" << endl;
cin >> choose;
switch (choose)
{
case 1:
cout << "请输入姓名:" << endl;
cin >> stu.name;
cout << "请输入年龄:" << endl;
cin >> stu.age;
cout << "请输入性别:" << endl;
cin >> stu.sex;
cout << "请输入要插入的位置:" << endl;
cin >> num;
if (listInsert(L, num, stu))
{
cout << "插入成功!" << endl;
}
else
{
cout << "输入位置不符合规定!" << endl;
}
break;
case 2:
findall(L);
break;
case 3:
cout << "请输入要查询的位置" << endl;
cin >> num1;
findElem(L, num1);
break;
case 4:
cout << "请输入要删除的位置" << endl;
cin >> num2;
deleteElem(L, num2);
break;
default:
cout << "输入错误,请重新输入" << endl;
break;
}
}
system("pause");
return 0;
}
2. 动态分配
#include <iostream>
#include <stdlib.h>
using namespace std;
#define initsize 10
typedef struct {
int *data;
int MaxSize;
int length;
}Node;
void initlist(Node &l){
l.data=(int *)malloc(initsize*sizeof(int));
l.length=0;
l.MaxSize=initsize;
}
void increaseSize(Node &l,int num){
int *p=l.data;
l.data=(int *)malloc((l.MaxSize+num)*sizeof(int));
for(int i=0;i<l.length;i++){
l.data[i]=p[i];
}
l.MaxSize=l.MaxSize+num;
for(int i=l.length;i<l.MaxSize;i++){
l.data[i]=i;
l.length++;
}
free(p);
}
int main(){
Node L;
initlist(L);
Node *l=&L;
for(int i=0;i<(*l).MaxSize;i++){
(*l).data[i]=i;
(*l).length++;
}
cout<<(*l).length;
cout<<"扩充前"<<endl;
for(int i=0;i<(*l).length;i++){
cout<<(*l).data[i]<<endl;
}
cout<<"请输入要扩充的大小:"<<endl;
int num;
cin>>num;
increaseSize((*l),num);
cout<<(*l).length<<endl;
cout<<"扩充后"<<endl;
for(int i=0;i<(*l).length;i++){
cout<<(*l).data[i]<<endl;
}
system("pause");
}