Sqlist.h头文件
#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
using namespace std;
#define SIZE 10
typedef int ElemType;
typedef struct SqList
{
ElemType* data;
int size;
int capacity;
}SL;
void InitList(SL& L);
void ListNewCapacity(SL& L);
void DataEntry(SL& L);
void PrintList(const SL& L);
void GetElem(const SL& L, int i, ElemType& e);
int LocateElem(const SL& L, ElemType e);
void ListInsert(SL& L, int i, ElemType e);
void ListRevise(SL& L, int i, ElemType e);
void ListDelete(SL& L, int i);
void DestroyList(SL& L);
SqList.cpp功能函数实现
#include "SqList.h"
void InitList(SL& L)
{
L.data = NULL;
L.size = 0;
L.capacity = 0;
}
void ListNewCapacity(SL& L)
{
if (L.size == L.capacity)
{
int NewCapacity = L.capacity == 0 ? SIZE : L.capacity * 2;
ElemType* ret = (ElemType*)realloc(L.data, NewCapacity * sizeof(ElemType));
if (ret == NULL)
{
cout << strerror(errno) << endl;
exit(-1);
}
else
{
L.data = ret;
L.capacity = NewCapacity;
}
}
}
void DataEntry(SL& L)
{
ListNewCapacity(L);
int i = 0;
int n = 0;
ElemType e;
cout << "请输入要顺序表中存放数据个数: ";
cin >> n;
for (i; i < n; i++)
{
cin >> e;
L.data[i] = e;
L.size++;
}
}
void PrintList(const SL& L)
{
if (L.size == 0)
{
cout << "顺序表中无数据" << endl;
}
else
{
for (int i = 0; i < L.size; i++)
{
cout << L.data[i] << " ";
}
cout << endl;
}
}
void GetElem(const SL& L, int i, ElemType& e)
{
assert(i > 0 && i <= L.size);
e = L.data[i - 1];
}
int LocateElem(const SL& L, ElemType e)
{
int i = 0;
for (i; i < L.size; i++)
{
if (L.data[i] == e)
{
return i + 1;
}
}
return 0;
}
void ListInsert(SL& L, int i, ElemType e)
{
assert(i > 0 && i <= L.size + 1);
ListNewCapacity(L);
int ret = L.size - 1;
for (ret; ret >= i - 1; ret--)
{
L.data[ret + 1] = L.data[ret];
}
L.data[i - 1] = e;
L.size++;
}
void ListRevise(SL& L, int i, ElemType e)
{
assert(i > 0 && i <= L.size);
L.data[i - 1] = e;
}
void ListDelete(SL& L, int i)
{
assert(i > 0 && i <= L.size);
int ret= i - 1;
for (ret; ret < L.size - 1; ret++ )
{
L.data[ret] = L.data[ret + 1];
}
L.size--;
}
void DestroyList(SL& L)
{
free(L.data);
L.data = NULL;
L.size = L.capacity = 0;
}