1
1
#include < iostream>
2
+ #include < initializer_list>
2
3
#ifndef __forwardList
3
4
#define __forwardList
4
5
template <typename T>
@@ -19,6 +20,20 @@ class forward_lists{
19
20
this ->head = nullptr ;
20
21
this ->size = 0 ;
21
22
}
23
+ /* *
24
+ * @brief initializer list constructor
25
+ * @details
26
+ */
27
+ forward_lists (std::initializer_list<T> arr): head(nullptr ){
28
+ Node** curr = &head; // store alamat memory head ke curr
29
+ for (const T& it: arr){
30
+ *curr = new Node (it); // deference pointer
31
+ // head = new Node(it) ->meaning
32
+ curr = &((*curr)->next ); // store alamat curr->next
33
+ // curr = head->next
34
+ // curr selalu menunjuk ke posisi kosong
35
+ }
36
+ }
22
37
// copy constructor
23
38
forward_lists (const forward_lists& others){
24
39
if (*this == &others){
@@ -62,22 +77,22 @@ class forward_lists{
62
77
private:
63
78
Node* node;
64
79
public:
65
- Iterator (Node n){
80
+ Iterator (Node* n){
66
81
this ->node = n;
67
82
}
68
- Iterator & operator *(){
83
+ T & operator *(){
69
84
return node->data ;
70
85
}
71
- T & operator ++(){
86
+ Iterator & operator ++(){ // harus mengembalikan reference ke object saat ini
72
87
if (node) node = node->next ;
73
88
return *this ;
74
89
}
75
- Iterator& operator ++(int ){
90
+ Iterator operator ++(int ){ // harus mengambalikan salin bukan referensi
76
91
Iterator temp = *this ; // simpan keadaan sebelum di geser
77
92
++(*this );// geser
78
93
return temp; // kembalikan keadaan sebelum di geser
79
94
}
80
- bool operator !=(const Iterator& others){
95
+ bool operator !=(const Iterator& others)const {
81
96
return node != others.node ;
82
97
}
83
98
};
@@ -140,13 +155,14 @@ class forward_lists{
140
155
curr->next = new_node;
141
156
}else {
142
157
Node* new_node = new Node (val);
143
- Node* temp = new_node;
144
- for (int i = 0 ;i < n;i++){
145
- Node* n_node = new Node (val);
146
- new_node->next = n_node;
158
+ Node* tail = new_node;
159
+ for (int i = 0 ;i < n - 1 ;i++){
160
+ Node* baru = new Node (val);
161
+ tail->next = baru;
162
+ tail = baru;
147
163
}
148
- new_node ->next = curr->next ;
149
- curr->next = temp ;
164
+ tail ->next = curr->next ;
165
+ curr->next = new_node ;
150
166
}
151
167
}
152
168
public:
0 commit comments