代码如下:
#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;//把0当做nullmaxSize = 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)//在i位置插入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)//删除i位置的元素,并把该元素的值返回给传入第二个位置的变量{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)//返回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)//判断元素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;
}
示例如下: