98 lines
3.1 KiB
C++
98 lines
3.1 KiB
C++
#ifndef Toolbox_CircularLinkedList_H
|
|
#define Toolbox_CircularLinkedList_H
|
|
|
|
namespace Toolbox {
|
|
template<typename T>
|
|
struct CircularLinkedListNode {
|
|
CircularLinkedListNode *prev = nullptr, *next = nullptr;
|
|
T data;
|
|
};
|
|
template<typename T>
|
|
class CircularLinkedList {
|
|
public:
|
|
CircularLinkedListNode<T> *mHead = nullptr;
|
|
CircularLinkedListNode<T> *mCur = nullptr;
|
|
void init(const QVector<T> &dataList) {
|
|
mHead = new CircularLinkedListNode<T>();
|
|
mHead->data = dataList.first();
|
|
CircularLinkedListNode<T> *prev = mHead;
|
|
int n = dataList.size();
|
|
for (int i = 1; i < n - 1; i++) {
|
|
auto node = new CircularLinkedListNode<T>();
|
|
node->data = dataList[i];
|
|
node->prev = prev;
|
|
prev->next = node;
|
|
prev = node;
|
|
}
|
|
auto tail = new CircularLinkedListNode<T>();
|
|
tail->data = dataList.last();
|
|
tail->prev = prev;
|
|
prev->next = tail;
|
|
tail->next = mHead;
|
|
mHead->prev = tail;
|
|
mCur = mHead;
|
|
}
|
|
CircularLinkedListNode<T> *move(int step = 1) {
|
|
if (step == 0) return nullptr;
|
|
return step > 0 ? next(step) : prev(-step);
|
|
}
|
|
CircularLinkedListNode<T> *next(int step = 1) {
|
|
if (step <= 0) return nullptr;
|
|
for (int i = 0; i < step; i++) {
|
|
mCur = mCur->next;
|
|
}
|
|
return mCur;
|
|
}
|
|
CircularLinkedListNode<T> *prev(int step = 1) {
|
|
if (step <= 0) return nullptr;
|
|
for (int i = 0; i < step; i++) {
|
|
mCur = mCur->prev;
|
|
}
|
|
return mCur;
|
|
}
|
|
void insert_next(const T &t, CircularLinkedListNode<T> *that = nullptr) {
|
|
if (that == nullptr) that = mCur;
|
|
auto node = new CircularLinkedListNode<T>();
|
|
node->data = t;
|
|
node->next = that->next;
|
|
node->prev = that;
|
|
that->next = node;
|
|
}
|
|
void insert_prev(const T &t, CircularLinkedListNode<T> *that = nullptr) {
|
|
if (that == nullptr) that = mCur;
|
|
auto node = new CircularLinkedListNode<T>();
|
|
node->data = t;
|
|
node->prev = that->prev;
|
|
node->next = that;
|
|
that->prev = node;
|
|
}
|
|
QVector<CircularLinkedListNode<T> *> to_vector() {
|
|
if (mHead == nullptr) return {};
|
|
QVector<CircularLinkedListNode<T> *> ret;
|
|
CircularLinkedListNode<T> *cur = mHead;
|
|
do {
|
|
ret.push_back(cur);
|
|
cur = cur->next;
|
|
} while (cur != mHead);
|
|
return ret;
|
|
}
|
|
void clear() {
|
|
if (mHead == nullptr) return;
|
|
CircularLinkedListNode<T> *cur = mHead;
|
|
do {
|
|
CircularLinkedListNode<T> *temp = cur;
|
|
cur = cur->next;
|
|
delete temp;
|
|
} while (cur != mHead);
|
|
mHead = nullptr;
|
|
}
|
|
~CircularLinkedList() {
|
|
clear();
|
|
}
|
|
};
|
|
}
|
|
#endif
|
|
|
|
|
|
|