embkernel
 All Classes Functions Variables Typedefs Groups Pages
LibLinkedList.hpp
1 //------------------------------------------------------------------------------
2 //This file is part of embKernel.
3 //See license.txt for the full license governing this code.
4 //------------------------------------------------------------------------------
5 
6 #ifndef LIB_LINKED_LIST_HPP_
7 #define LIB_LINKED_LIST_HPP_
8 
9 #include "LibMacros.hpp"
10 
11 
12 template<class T>
13 class LibLinkedList {
14 private:
15  T* mFirst;
16  T* mLast;
17  int count;
18 public:
19  LibLinkedList();
20  ~LibLinkedList();
21 
22  void insert(T& item);
23  void remove(T& item);
24  T* getFirst();
25  T* getLast();
26 };
27 
28 template<class T>
29 class LIB_LINKED_LIST_ITERABLE {
30  friend class LibLinkedList<T>;
31 private :
32  T* mPrev;
33  T* mNext;
34 protected:
35  LIB_LINKED_LIST_ITERABLE();
36  ~LIB_LINKED_LIST_ITERABLE();
37 public:
38  T* getPrev();
39  T* getNext();
40 };
41 
42 
43 template<class T>
44 LIB_LINKED_LIST_ITERABLE<T>::LIB_LINKED_LIST_ITERABLE() {
45  mPrev = 0;
46  mNext = 0;
47 }
48 
49 template<class T>
50 LIB_LINKED_LIST_ITERABLE<T>::~LIB_LINKED_LIST_ITERABLE() {
51  //Object must be removed from list before being destroyed
52  LIB_ASSERT(mPrev == 0);//
53  LIB_ASSERT(mNext == 0);//
54 }
55 
56 template<class T>
57 T* LIB_LINKED_LIST_ITERABLE<T>::getPrev() {
58  return mPrev;
59 }
60 
61 template<class T>
62 T* LIB_LINKED_LIST_ITERABLE<T>::getNext() {
63  return mNext;
64 }
65 
66 template<class T>
67 LibLinkedList<T>::LibLinkedList() {
68  mFirst = 0;
69  mLast = 0;
70  count = 0;
71 }
72 
73 template<class T>
74 LibLinkedList<T>::~LibLinkedList() {
75 }
76 
77 template<class T>
78 void LibLinkedList<T>::insert(T& item) {
79  if (mLast) {
80  mLast->mNext = &item;
81  item.mPrev = mLast;
82  mLast = &item;
83  }
84  else {
85  item.mPrev = 0;
86  mFirst = &item;
87  mLast = &item;
88  }
89  item.mNext = 0;
90  count++;
91 }
92 
93 template<class T>
94 void LibLinkedList<T>::remove(T& item) {
95  T* prev = item.mPrev;
96  T* next = item.mNext;
97 
98  //Is this the first item in the list
99  if (!prev) {
100  //Is this the only item in the list
101  if (!next) {
102  mFirst = 0;
103  mLast = 0;
104  }
105  else {
106  mFirst = next;
107  next->mPrev = 0;
108  }
109  }
110  //Is this the last item in the list
111  else if (!next) {
112 
113  mLast = prev;
114  prev->mNext = 0;
115  }
116  //Otherwise we are in the middle of the list
117  else {
118  prev->mNext = next;
119  next->mPrev = prev;
120  }
121 
122  item.mPrev = 0;
123  item.mNext = 0;
124 
125  count--;
126 }
127 
128 template<class T>
129 T* LibLinkedList<T>::getFirst() {
130  return mFirst;
131 }
132 
133 template<class T>
134 T* LibLinkedList<T>::getLast() {
135  return mLast;
136 }
137 
138 
139 #endif /* LIB_LINKED_LIST_HPP_ */