代码如下:
#include <iostream>
using namespace std;
const int N = 100;
struct Node
{
int data;
int next;
};
class ArrayList
{
private:
Node node[N];
int maxSize;
int idx;
int len;
public:
void initList()
{
node[0].next = 0;
maxSize = N;
len = 0;
}
bool createList(int n)
{
if (n > N - 1) return false;
int x;
for (int i = 0; i < n; i++)
{
cin >> x;
node[i].next = i + 1;
node[i + 1].data = x;
node[i + 1].next = 0;
}
idx = n+1;
len = 5;
return true;
}
bool insertList(int i, int e)
{
if (idx == maxSize) return false;
if (i < 1 || i > len+1 ) return false;
if (i == 1)
{
node[idx].data = e;
node[idx].next = 0;
node[idx].next = node[0].next;
node[0].next = idx;
idx++;
len++;
return true;
}
int cnt = 0;
for (int p = node[0].next; p != 0; p = node[p].next)
{
cnt++;
if (cnt == i - 1)
{
node[idx].data = e;
node[idx].next = 0;
node[idx].next = node[p].next;
node[p].next = idx;
idx++;
len++;
return true;
}
}
return true;
}
bool deleteList(int i, int &e)
{
if (i < 1 || i > len) return false;
if (len == 0) return false;
if (i == 1)
{
node[0].next = node[node[0].next].next;
len--;
}
int cnt = 0;
for (int p = node[0].next; p != 0; p = node[p].next)
{
cnt++;
if (cnt == i - 1)
{
node[p].next = node[node[p].next].next;
len--;
return true;
}
}
return true;
}
int locateElem(int e)
{
int cnt = 0;
for (int i = node[0].next; i != 0; i = node[i].next)
{
cnt++;
if (node[i].data == e)
{
return cnt;
}
}
}
bool isElem(int e)
{
for (int i = node[0].next; i != 0; i = node[i].next)
{
if (node[i].data == e)
{
return true;
}
}
return false;
}
void printList()
{
for (int i = node[0].next; i != 0; i = node[i].next)
{
cout << node[i].data << " ";
}
cout << endl;
}
};
int main()
{
ArrayList l;
l.createList(5);
l.insertList(1, 3);
l.insertList(2, 6);
int a;
l.deleteList(1, a);
l.deleteList(2, a);
l.insertList(1, 3);
l.insertList(2, 6);
cout << l.isElem(33) << endl;
cout << l.isElem(23) << endl;
cout << l.locateElem(33) << endl;
l.printList();
return 0;
}
示例如下:
|