I'm currently in the middle of studying for my Programming 2 finals, which essentially is a practical test about data structures and sorting algorithms.
We've been taught by a C programmer who showed us only the implementation with head as a private member. I've experimented a bit and have come up with two other approaches, but I'm not sure about which one I should use when I write linked lists.
Approach #1
structs
This is a slightly different spin on what we've seen in class. I've added a ctor (the professor didn't because "structs can't have methods", in his own words)
1 2 3 4 5 6 7 8
|
template <typename T>
struct Node {
Node(T data) {
this->data = data;
this->next = nullptr;
T data;
Node *next;
}
|
Pros:
- Quick to implement
- No need for defining getters and setters
Cons:
- Pretty much no encapsulation
Approach #2
classes
Similar to the struct approach, but this one uses public getters and setters and a private variable data and pointer to the next element
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
template <typename T>
class Node {
public:
Node(T data) {
this->data = data;
this->next = nullptr;
}
void set_data(T data) { this->data = data; }
void set_next(Node *next) { this->next = next; }
T get_data() const { return data; }
Node* get_next() const { return next; }
private:
T data;
Node *next;
}
|
Pros:
- Encapsulation
Cons:
- More code to type
- Slightly awkward syntax[/code]
Approach #3
friend class
This is what I found myself using the most.
1 2 3 4 5 6 7 8 9 10
|
template <typename T>
class Node {
friend class List<T>;
Node(T data) {
this->data = data;
this->next = nullptr;
}
T data;
Node *next;
}
|
Pros:
- Best encapsulation of all (cannot instantiate nodes outside of a List)
- Quick to write
Cons:
- Not easily extensible (friendliness doesn't extend to classes derived from List)
Does anyone know of any other approaches to writing nodes? And what do you guys think about the ones I described?