顺序表的实现
//还有很多缺陷,但学顺序表的话,知道这些就足够了#include <cstdlib>
#include <iostream>
using namespace std;
#define list_init_size 100
#define listincreament 10
typedef struct
{
int *elem;
int length;
int listsize;
}sqList; //顺序存储结构表
void initSqList (sqList &L)
{
L.elem = (int*)malloc (list_init_size *sizeof(int));
if (!L.elem) exit(0);
L.length = 0;
L.listsize = list_init_size;
}
void insertSqList (sqList &L,int e) // 插入元素,插入并没有排序
{
if (L.length >= L.listsize)
{
int* newbase = (int*)realloc(L.elem, (L.listsize + listincreament)*sizeof(int));
if (!newbase) exit(0);
L.elem = newbase;
L.listsize += listincreament;
}
L.elem[L.length] = e;
++L.length;
}
bool findSqList( sqList L, int e)
{
bool b = false;
for (int i = 0; i < L.length; i ++, L.elem ++)
{
if (*(L.elem) == e) b = true;
}
return b;
}
void delSqList (sqList &L, int e) // 删除元素,对于重复的元素只能删一个 ,不能删除不
{
if (findSqList (L, e))
{
int *p;
int i = 0;
p = L.elem;
while (*p != e)
{
i++;
p++;
}
int *q;
q = L.elem + i;
for (; i < L.length; ++i, p++) *p = *(p+1);
--L.length;
}
else
cout << e << " is not the number of the list." << endl;
}
void printSqList (sqList L)
{
int *p;
p = L.elem;
for(int i = 0; i < L.length; i++)
{
cout << *p << '\t';
p++;
}
cout << endl;
}
int main(int argc, char *argv[])
{
sqList L;
int n, m;
initSqList(L);
cout << "please input the number you want to input(-1 with end) :"<< endl;
cin >> n;
while ( n != -1)
{
insertSqList (L, n);
cin >> n;
}
cout << "The list of number is : " << endl;
printSqList(L);
cout << "which of the number in the list do you want to delete(-1 with end): " << endl;
cin >> n;
while ( n != -1)
{
delSqList (L, n);
printSqList(L);
cout << "which of the number in the list do you want to delete(-1 with end): " << endl;
cin >> n;
}
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}