blob: c157c31d16c03e2543a82d6cb72f72e0d1fe5f33 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkSinglyLinkedList_DEFINED
#define SkSinglyLinkedList_DEFINED
#include <utility>
#include "SkTypes.h"
template <typename T> class SkSinglyLinkedList {
struct Node;
public:
SkSinglyLinkedList() : fHead(nullptr), fTail(nullptr) {}
~SkSinglyLinkedList() { this->reset(); }
void reset() {
SkASSERT(fHead != nullptr || nullptr == fTail);
Node* node = fHead;
while (node) {
Node* next = node->fNext;
SkASSERT(next != nullptr || node == fTail);
delete node;
node = next;
}
fHead = nullptr;
fTail = nullptr;
}
T* back() { return fTail ? &fTail->fData : nullptr; }
T* front() { return fHead ? &fHead->fData : nullptr; }
#ifdef SK_DEBUG
int count() { // O(n), debug only.
int count = 0;
for (Node* node = fHead; node; node = node->fNext) {
++count;
}
return count;
}
#endif
void pop_front() {
if (Node* node = fHead) {
fHead = node->fNext;
delete node;
if (fHead == nullptr) {
fTail = nullptr;
}
}
}
template <class... Args> T* emplace_front(Args&&... args) {
Node* n = new Node(std::forward<Args>(args)...);
n->fNext = fHead;
if (!fTail) {
fTail = n;
SkASSERT(!fHead);
}
fHead = n;
return &n->fData;
}
template <class... Args> T* emplace_back(Args&&... args) {
Node* n = new Node(std::forward<Args>(args)...);
if (fTail) {
fTail->fNext = n;
} else {
fHead = n;
}
fTail = n;
return &n->fData;
}
class ConstIter {
public:
void operator++() { fNode = fNode->fNext; }
const T& operator*() const { return fNode->fData; }
bool operator!=(const ConstIter& rhs) const { return fNode != rhs.fNode; }
ConstIter(const Node* n) : fNode(n) {}
private:
const Node* fNode;
};
ConstIter begin() const { return ConstIter(fHead); }
ConstIter end() const { return ConstIter(nullptr); }
private:
struct Node {
T fData;
Node* fNext;
template <class... Args>
Node(Args&&... args) : fData(std::forward<Args>(args)...), fNext(nullptr) {}
};
Node* fHead;
Node* fTail;
SkSinglyLinkedList(const SkSinglyLinkedList<T>&) = delete;
SkSinglyLinkedList& operator=(const SkSinglyLinkedList<T>&) = delete;
};
#endif // SkSinglyLinkedList_DEFINED
|