Reputation: 111
So I understand (mostly) the concept of linked lists with pointers. However, I am not sure how I would be able to create a linked list of a struct object, that is passed in a method. Do I need another pointer to point to the pointers on the struct? My struct contains the pointer:
// define a structure to hold bid information
struct Bid {
string bidId; // unique identifier
string title;
string fund;
double amount;
Bid *next;
Bid() {
amount = 0.0;
next = NULL;
}
};
And I am passing the struct object to this method to append new Bid structs:
void LinkedList::Append(Bid bid) {
// FIXME (3): Implement append logic
//reference bid being passed??? Bid struct has pointers, do we need another pointer?
Bid *currNode = &bid;
//set node's next pointer to NULL (end)
currNode->next = NULL;
//if list is empty
if (head == NULL) {
head = currNode;
tail = currNode;
}
else {
tail->next = currNode;
tail = currNode;
}
}
Upvotes: 1
Views: 766
Reputation: 41454
The problem with passing linked list nodes around by value is that they get copied. You can set a pointer to point to the bid
value in your function, but that's almost certainly not what you want, because it's going to go away at the end of the function, leaving the pointer dangling. Linked list nodes are virtually always heap-allocated, and passed around by pointer, because you can manually control the lifetime of heap-allocated objects (which is essential here).
Now, what makes this a little problematic from an OO standpoint is that your Bid
class is violating the Single Responsibility Principle (SRP), in that it's being both a storage for concrete information about a bid and a participant in linking certain Bids together. This is one of the reasons you rarely see intrusive containers in OO languages. Depending on your exact use case, it could be preferable to store a pointer-less Bid
in a BidNode
which would do the linking. If you did that, you could pass around the Bid
by value, and copy it into a heap-allocated BidNode
. Or, of course, you could just use std::list
.
Upvotes: 2