建立源文件SeqList.cpp:
#define _CRT_SECURE_NO_WARNINGS 1 #include"SeqList.h" int main() { Test(); system("pause"); return 0; }
建立源文件SeqList.h:
#ifndef __SEQLIST_H__ #define __SEQLIST_H__ #include<iostream> using namespace std; #include<assert.h> typedef int DataType; class SeqList { public: SeqList() :_arr(NULL) , _size(0) , _capacity(0) {} SeqList(const SeqList& s) :_size(s._size) , _capacity(s._capacity) { memcpy(_arr, s._arr, sizeof(DataType)* s._size); } SeqList& operator= (const SeqList& s) { if (this != &s) { DataType* tmp = new DataType[s._size]; memcpy(tmp, s._arr,sizeof(DataType) * s._size); delete _arr; _arr = NULL; _arr = tmp; _size = s._size; _capacity = s._capacity; } return *this; } ~SeqList() { if (_arr) { delete _arr; _arr = NULL; } } void PushBack(DataType x) { // 0 1 多 _CheckCapacity(); if (_size == 0) { _size = 1; _arr[0] = x; } else { _arr[_size++] = x; } } void PrintSeqList() { for (int i = 0; i < _size; i++) { cout << _arr[i] << " "; } cout << endl; } void PopBack() { if (_size == 0) { return; } else { _size--; } } void PushFront(DataType x) { _CheckCapacity(); if (_size == 0) { ++_size; _arr[0] = x; return; } ++_size; for (int i = _size - 2; i >= 0; i--) { _arr[i + 1] = _arr[i]; } _arr[0] = x; } void PopFront() { if (_size == 0) { return; } for (int i = 1; i < _size; i++) { _arr[i - 1] = _arr[i]; } --_size; } void Insert(size_t pos, DataType x) { if (_size == pos) { PushBack(x); return; } ++_size; for (int i = _size; i > pos; i--) { _arr[i] = _arr[i - 1]; } _arr[pos] = x; } int Find(DataType x) { int i = 0; while (i <= _size) { if (_arr[i] == x) { return i; } i++; } return -1; } void _CheckCapacity() { if (_size >= _capacity) { _capacity = 2 * _capacity + 3; _arr = (DataType*)realloc(_arr, sizeof(DataType)* _capacity); } } private: size_t _capacity; size_t _size; DataType* _arr; }; void Test() { SeqList s; s.PushBack(1); s.PushBack(2); s.PushBack(3); s.PushBack(4); s.PrintSeqList(); s.PopBack(); s.PrintSeqList(); s.PushFront(0); s.PrintSeqList(); s.PopFront(); s.PrintSeqList(); s.Insert(3, 10); s.PrintSeqList(); int ret = s.Find(10); printf("%d\n", ret); } #endif //__SEQLIST_H__
时间: 2024-10-11 15:17:30