线性表——顺序存储结构

来源:互联网 发布:中原 知乎 编辑:程序博客网 时间:2024/06/03 04:47
#ifndef ARRAYLIST_H#define ARRAYLIST_H#include <stdint.h>#include <stdio.h>#include <stdlib.h>template <typename DataType>class ArrayList {public:    ArrayList(uint32_t _length) :        max_length(_length) {        length = 0;    }    ~ArrayList() {        delete [] item;    }public:    void InitList(void) {        item = new DataType[max_length];    }    bool ListEmpty(void) {        if (length == 0) {            return true;        } else {            return false;        }    }    void ClearList(void) {        for (uint32_t i = 0; i < length; ++i) {            item[i] = NULL;        }        length = 0;    }    void GetElem(uint32_t i, DataType *e) {        if ((length == 0) || (i > length)) {            fprintf(stderr, "Out of array!\n");        } else {            *e = item[i-1];        }    }    uint32_t LocateElem(DataType e) {        for (uint32_t i = 1; i <= length; ++i) {            if ((item[i-1] != NULL) && (item[i-1] == e)) {                return i;            }        }        fprintf(stderr, "Not in array!\n");    }    void ListInsert(uint32_t i, DataType *e) {        if (length == max_length) {            fprintf(stderr, "Array is full!\n");            return;        }        if ((i < 1) || (i > length + 1)) {            fprintf(stderr, "Out of array!\n");            return;        }        if (i <= length) {            for (int j = length-1; j >= i-1; --j) {                item[j+1] = item[j];            }        }        item[i-1] = *e;        ++length;    }    void ListDelete(uint32_t i, DataType *e) {        if (length == 0) {            fprintf(stderr, "array has empty!\n");        }        if ((i < 1) || (i > length)) {            fprintf(stderr, "out of array!\n");        } else {            *e = item[i-1];            int j = i;            for (; j < ListLength(); ++j) {                item[j-1] = item[j];            }            --length;        }    }    uint32_t ListLength() {        return length;    }private:    DataType *item;    uint32_t max_length;    uint32_t length;};#endif

0 0
原创粉丝点击