samedi 3 mars 2018

Initializing a doubly linked list from array parameters

C++ noob reporting in. I'm trying to write a function that will create and initialize a doubly linked list using values that are stored in two different arrays. Here's how my linked list class is set up:

class node {
   public:
   node *prev;
   node *next;
   int key;
   char type;
};

and here's how my dList class (containing various functions to alter my linked list) is set up:

class dList {
private:
   node *head; // dummy head
   node *tail; // dummy tail

public:
   dList() { // default constructor, creates empty list
     head = tail = NULL;
   }

   ~dList() { // deconstructor
     node *ptr = head;
     while (head != NULL) {
       head = head->next;
       delete ptr;
     }
     tail = NULL;
   }

   dList(int arrayNums[], char arrayChars[], int size); // parametrized constructor, initialize list w/ contents of arrays

   void addFront(int k, char t); // creates new node at front of list

   void addBack(int k, char t); // creates new node at back of list

   node *search(int k); // searches list for occurence of int parameter and returns pointer to node containing key

   void find(char t); // outputs all keys that have type equal to character parameter, front to back

   void moveFront(node* ptr); // moves node pointed to by parameter to front of list

   void moveBack(node* ptr); // moves node pointed to by parameter to back of list

   void out(int num, char = 'f'); // outputs first int elements of list, starting at front or back depending on char parameter

   void sort(); // peforms a quick or mergesort on items; list should be in increasing order based on integer key

};

I need help implementing my parametrized constructor. Could someone tell me if the function I have now is written correctly? I think it is, but when I run my program, it runs forever--a clear problem. Here's my function as-is:

dList::dList(int arrayNums[], char arrayChars[], int size) { 
  node *newNode = NULL;

  for (int i = 0; i < size; i++) {

    if (head == NULL) {
      newNode = new node;
      newNode->key = arrayNums[i];
      newNode->type = arrayChars[i];
      newNode->prev = NULL;
      newNode->next = NULL;
      head = newNode;
      tail = newNode;
    }

    else { // needs work!
      newNode = new node;
      newNode->key = arrayNums[i];
      newNode->type = arrayChars[i];
      newNode->prev = tail;
      tail->next = newNode;
      tail = newNode;
    }

    if (i == (size - 1)) {
      tail->next = NULL;
    }
  }
}

Thank you very much!

Aucun commentaire:

Enregistrer un commentaire