繁体   English   中英

在C ++中实现双向链表副本构造函数

[英]Implementing a doubly linked list copy constructor in C++

我在弄清楚如何为双向链表实现副本构造函数时遇到了麻烦。 我相信,到目前为止我所拥有的代码是不正确的,因为我无法跟踪标头节点,但是我不确定该如何纠正。 任何帮助将非常感激!

DoublyLinkedList.h

#include <cstdlib>
#include <iostream>
using namespace std;
class DoublyLinkedList; // class declaration

// list node
class DListNode {
private: 
    int obj;
    DListNode *prev, *next;
    friend class DoublyLinkedList;
public:
    DListNode(int e = 0, DListNode *p = NULL, DListNode *n = NULL)
        : obj(e), prev(p), next(n) {}

    int getElem() const { return obj; }
    DListNode * getNext() const { return next; }
    DListNode * getPrev() const { return prev; }
};

// doubly linked list
class DoublyLinkedList {
protected: 
    DListNode header, trailer;
public:
    DoublyLinkedList() : header(0), trailer(0) // constructor
        { header.next = &trailer; trailer.prev = &header; }
    DoublyLinkedList(const DoublyLinkedList& dll); // copy constructor
    ~DoublyLinkedList(); // destructor
    DoublyLinkedList& operator=(const DoublyLinkedList& dll); // assignment operator


    DListNode *getFirst() const { return header.next; } // return the pointer to the first node
    const DListNode *getAfterLast() const { return &trailer; }  // return the pointer to the trailer
    bool isEmpty() const { return header.next == &trailer; } // return if the list is empty
    int first() const; // return the first object
    int last() const; // return the last object

    void insertFirst(int newobj); // insert to the first of the list
    int removeFirst(); // remove the first node
    void insertLast(int newobj); // insert to the last of the list
    int removeLast(); // remove the last node

};

// output operator
ostream& operator<<(ostream& out, const DoublyLinkedList& dll);

DoublyLinkedList.cpp-复制构造函数

// copy constructor
DoublyLinkedList::DoublyLinkedList(const DoublyLinkedList& dll)
{
  // Initialize the list
  header = 0;
  trailer = 0;
  header.next = &trailer; 
  trailer.prev = &header;

  // Copy from dll
    DListNode* head = new DListNode;
    head->prev = dll.header.prev;
    head->obj = dll.header.obj;
    head->next = dll.header.next;

    DListNode* tail = new DListNode;
    tail->prev = dll.trailer.prev;
    tail->obj = dll.trailer.obj;
    tail->next = dll.trailer.next;

    DListNode* curr = new DListNode;
    curr->prev = head;

    while(curr != tail) {

        DListNode* n = new DListNode;
        curr->next = n;
        n = curr->prev->next;
        curr = curr->next;
    }

    curr = tail;
}

与其编写特定的代码以使用内部结构在dll中复制列表,不如不像通常那样循环遍历dll中的列表(使用dll.getFirst()和dll.getAfterLast())并仅使用每个值调用insertLast 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM