链接列表赋值运算符

时间:2010-11-01 14:52:14

标签: c++ linked-list

我正在试图弄清楚我是否对使用当前节点(没有正面或背面)的双重链接列表的赋值运算符有了一般的想法。这是我的伪代码。我需要理解这个概念。如果有人可以提供帮助,那就太好了。

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->back = temp->back
        receiver->entry = temp->entry
        receiver->next = null

这是我的节点结构:

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);

}

我不是在寻找代码答案,而是一种算法(实际上,评论和编写的代码实例很好)。我只需要了解复制的工作原理。

1 个答案:

答案 0 :(得分:0)

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;
}