Struggling to implement doubly linked list .h file(especiallucopy constructor and delete function)

deleted
Last edited on
In your insert function you keep forgetting the pred member of Node. It is neither set to nullptr (it remains uninitialized) nor is it linked. That is the reason why remove doesn't work.

On line 91 and line 111 you have basically the same loop twice. In the first loop you just count and in the second you kind of insert the node. This is unnecessary. The list is already sorted. Just insert where if (temp->ssn > temp->succ->ssn ) in the first loop.

I suggest that you make a constructor and a destructor for Node. In the constructor you set the members pred and succ to nullptr and in the destructor you simply delete succ. Then in the destructor of DLL you just need to delete headPtr;. Using pred there doesn't make sense (and will crash due to pred being uninitialized).
You can simplify this by writing a few utility methods. coder777 already suggested constructor/destructor for Node. You might also write:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class DLL
{
    private:
  
    // Insert "node" after the node pointed to by "after".
    // If "after" is null then insert node at the beginning.
    // This also increments itemCount.
    void insertAfter(Node *node, Node *after);

    // Remove "node," delete it, and decrement itemCount.  Don't forget
    // to set node->succ to nullptr before deleting it or it will
    // delete everything that comes after it too.
    void remove(Node *node);

    // Find the node with ssn == ss.  If found, return true, set
    // "count" to its position in the list (first item == 0), and set
    // "prev" to the previous node (or nullptr if there is none).
    // Otherwise return false, set "prev" to the node that it ss would
    // be inserted after (or nullptr if it should be inserted at the
    // beginning), and set count to the position where it would be
    // inserted.
    bool find(const string &ss, int &count, Node * &prev) const;
    ...
}


Once you have these, search(), insert() and remove() all become very simple. They all start with a call to find(). For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool
DLL::insert(string ss, string name, int &count)
{
    Node *prev;
    int cnt;

    if (find(ss, cnt, prev)) {
        return false;
    }

    // Node not found. Prev indicates where it should be inserted
    // and cnt gives the position where it will be inserted.
    Node *newPtr = new Node(ss, name);
    insertAfter(newPtr, prev);
    count = cnt;
    return true;
}

Search() and remove() are even easier. And the copy constructor turns into a series of calls to insertAfter().
Topic archived. No new replies allowed.