顺序表子函数

来源:互联网 发布:c语言生成随机数 编辑:程序博客网 时间:2024/06/06 01:01
#include<iostream>#include<stdlib.h>typedef int ElemType;struct List{ElemType *list;int size;int Maxsize;};void InitList(List &L){L.Maxsize = 10;L.list = new ElemType[L.Maxsize];if (L.list == NULL){std::cout << "动态可分配的存储空间用完,退出运行" << std::endl;exit(1);}L.size = 0;}void ClearList(List &L){if (L.list != NULL){     delete []L.list; L.list = NULL;}L.Maxsize = 0;L.size = 0;}int LenthList(List &L){return L.size;}bool EmptyList(List &L){return L.size == 0;}ElemType GetList(List &L, int pos){if (pos<1 || pos>L.size){std::cerr << "pos is out range!" << std::endl;exit(1);}return L.list[pos - 1];}void TraverseList(List &L){for (int i = 0; i < L.size; i++)std::cout << L.list[i] << ' ';std::cout << std::endl;}bool FindList(List &L, ElemType& item){for (int i = 0; i < L.size; i++)if (L.list[i] == item){item = L.list[i];return true;}return false;}bool InsertList(List &L, ElemType item, int pos){if (pos<-1 || pos>L.size){std::cout << "pos值无效!" << std::endl;return false;}int i;if (pos == 0){for (i = 0; i < L.size; i++)if (item < L.list[i])break;pos = i + 1;}else if (pos == -1)pos = L.size + 1;if (L.size == L.Maxsize) {int k = sizeof(ElemType);L.list = (ElemType*)realloc(L.list, 2 * L.Maxsize*k);if (L.list == NULL){std::cout << "动态可分配的储存空间用完,退出运行!" << endl;exit(1);}L.Maxsize = 2 * L.Maxsize;}for (i = L.size - 1; i >= pos - 1; i--)L.list[i + 1] = L.list[i];L.list[pos - 1] = item;L.size++;return true;}

原创粉丝点击