Linked-list assignment operator
I'm trying to figure out if i have the general idea behind the assignment operator for Doubly Linked Lists using a current node (no front or back). This is my pseudo code. I need to get this concept down. If anyone can help, that would be sweet.
Loop to start
temp = temp->back
loop to count
if 0
receiver->back = null
receiver->entry = temp->entry
receiver->next = temp->next
if > 0
receiver->back = temp->back
receiver->entry = temp->entry
receiver->next = temp->next
if == count-1
receiver->bac开发者_如何学JAVAk = temp->back
receiver->entry = temp->entry
receiver->next = null
This is my Node structure:
struct Node {
// data members
Node_entry entry;
Node<Node_entry> *next;
Node<Node_entry> *back;
// constructors
Node();
Node(Node_entry, Node<Node_entry> *link_back = nullptr,
Node<Node_entry> *link_next = nullptr);
}
I'm not looking for a code answer, but an algorithm (actually code that is well commented and written is good as example). I just need to understand how the copying works.
struct Node {
Node *prev, *next;
int entry;
explicit Node(int entry) : prev (0), next (0), entry (entry) {}
};
Node* copy_list(Node *node) {
assert(node); // require a non-null pointer
// copy "current" node
Node *new_list = new Node(node->entry);
// copy backward from node to beginning
Node *dest = new_list;
for (Node *x = node->prev; x; x = x->prev) {
dest->prev = new Node(x->entry);
dest->prev->next = dest;
dest = dest->prev;
}
// copy forward from node to end
dest = new_list;
for (Node *x = node->next; x; x = x->next) {
dest->next = new Node(x->entry);
dest->next->prev = dest;
dest = dest->next;
}
return new_list;
}
精彩评论