- 最后登录
- 2016-10-1
- 注册时间
- 2013-12-28
- 阅读权限
- 90
- 积分
- 5805
- 纳金币
- 2954
- 精华
- 3
|
#ifndef __ArrayDemo__LWArray__
#define __ArrayDemo__LWArray__
#include <iostream>
#include <strstream>
template <typename T> struct LWArrayObject {
public:
T data;
LWArrayObject <T> * next;
};
template <typename T> class LWArray {
public:
int count;
public:
void addObject(T t);
void insertObject(int index, T t);
void removeObject(int index);
void replaceObject(int index, T t);
T getObject(int index);
void clear();
T getFirstObject();
T getLastObject();
std::string toString();
private:
LWArrayObject <T> * firstObject;
LWArrayObject <T> * lastObject;
};
template <typename T> void LWArray<T>::insertObject(int index, T t) {
LWArrayObject <T> * o = new LWArrayObject <T> ();
o -> data = t;
o -> next = nullptr;
LWArrayObject <T> * obj = firstObject;
LWArrayObject <T> * lastObj = nullptr;
if (index > 0) {
while (index > 0) {
lastObj = obj;
obj = obj -> next;
index--;
}
lastObj -> next = o;
o -> next = obj;
} else if (index == 0) {
firstObject = o;
o -> next = obj;
}
count++;
}
template <typename T> void LWArray<T>::clear() {
while (count > 0) {
removeObject(0);
}
}
template <typename T> T LWArray<T>::getFirstObject() {
return firstObject -> data;
}
template <typename T> T LWArray<T>::getLastObject() {
return lastObject -> data;
}
template <typename T> T LWArray<T>::getObject(int index) {
LWArrayObject <T> * obj = firstObject;
while (index > 0) {
obj = obj -> next;
index--;
}
return obj -> data;
}
template <typename T> void LWArray<T>::replaceObject(int index, T t) {
LWArrayObject <T> * obj = firstObject;
while (index > 0) {
obj = obj -> next;
index--;
}
obj -> data = t;
}
template <typename T> void LWArray<T>::removeObject(int index) {
LWArrayObject <T> * obj = firstObject;
LWArrayObject <T> * lastObj = nullptr;
if (index > 0) {
while (index > 0) {
lastObj = obj;
obj = obj -> next;
index--;
}
lastObj -> next = obj -> next;
} else if (index == 0) {
firstObject = obj -> next;
}
count--;
delete obj;
obj = nullptr;
}
template <typename T> void LWArray<T>::addObject(T t) {
LWArrayObject <T> * obj = new LWArrayObject <T> ();
obj -> data = t;
obj -> next = nullptr;
if (firstObject == nullptr) {
firstObject = obj;
}
if (lastObject != nullptr) {
lastObject -> next = obj;
}
lastObject = obj;
count++;
}
template <typename T> std::string LWArray<T>::toString() {
std::strstream ss;
ss << "Array(" << count << ")=[";
LWArrayObject <T> * obj;
for (int i = 0;i < count;i++) {
if (i == 0) {
obj = firstObject;
ss << obj -> data;
} else {
obj = obj -> next;
ss << "," << obj -> data;
}
}
ss << "]";
std::string str;
ss >> str;
return str;
}
#endif
|
|