dimanche 21 avril 2019

Doubly Circular Linked List insertNode Implementation

What my program does is read college name list from the data and save each name as a separate node and while inserting them, I need to sort it in alphabetical order. My code worked perfectly fine with singly linked list. However, after I implement insertNode function for doubly circular linked list; I am having access violation problem some how. Be aware that I am using one sentinel node at the beginning of the list. Please look at my code and tell me what should I do. Thank you!

CollegeList::CollegeList()
{
    head = new ListNode; // head points to the sentinel node
    head->next = NULL;
head->prev = NULL;
    count = 0;
}

bool CollegeList::insertNode(College dataIn)
{
    ListNode *newNode;  // A new node
    ListNode *pCur;     // To traverse the list
    ListNode *pPre;     // The previous node
bool inserted = false;

// Allocate a new node and store num there.
newNode = new ListNode;
newNode -> col = dataIn;
// Initialize pointers
pPre = head;
pCur = head->next;

//Find location: skip all nodes whose name is less than dataIn's name.
while(pCur != head && pCur -> col < dataIn)
{
    pPre = pCur;
    pCur = pCur -> next;
}

// Insert the new node between pPre and pCur
if (pCur == head) {
    pPre->next = newNode;
    newNode->prev = pPre;
    newNode->next = head;
    head->prev = newNode;
}
else {
    pCur = pPre->next;
    newNode->next = pCur;
    newNode->prev = pPre;
    pPre->next = newNode;
    pCur->prev = newNode;
}
inserted = true;
//Update the counter
count++;
return inserted;

}

class CollegeList
{
private:
    struct ListNode{
    College col;
    ListNode *next;
    ListNode *prev;
    };
    ListNode *head;
    int count;

public:
    //Constructor
    CollegeList();

    // Linked list operations
    bool insertNode(College);
    bool deleteNode(College);
    bool searchList(College, College &);
    void displayList() const;
    int getCount() {return count;}
bool traverseForward();
bool traverseBackward();
bool isEmpty();


    //Destructor
    ~CollegeList();
};

Aucun commentaire:

Enregistrer un commentaire