mercredi 26 juin 2019

Problem with linkage in a Doubly Linked List

I am trying to implement a doubly linked list with the following API :

  • bool empty(); // is the list empty?
  • void append(char c); // inserts the character c at the back of the list
  • int size(); // the number of elements in the list
  • string toString(); // return the list as a string.
  • CharList(string s); // constructor. Initializes the list to the contents of the string.
  • ~CharList(); // destructor. Returns all memory in the list.

I have a really persistent bug where my pointers from the header node. to the next link are not working The problem manifests itself when I use the toString function.The problem manifests itself when I use the toString function.

My constructor ( with a default argument of s = "" ) calls on the append function and is shown below. I have also shown the toString function too.

I have tried using the trailer for the toString function and can confirm that indeed I do get the string back ( although it will be reversed which would be an easy fix.

CharList::CharList(string s)
{
  count = 0;
  header = new CharListNode;
  trailer = new CharListNode;
  int length = s.length();
  header->next = trailer;
  trailer->prev = header;
  if(length == 0)
  {
    return;
  }
   const char* c_string = s.c_str();
   for(int i = 0; i<length; i++)
   {
     char letter = c_string[i];
     CharList::append(letter);
   }
}

void CharList::append(char c)
{
  CharListNode *z = new CharListNode;
  z->element = c;
  z->next = this->trailer;
  z->prev = this -> trailer->prev;
  this->trailer->prev->next = z;
  trailer->prev = z;
  count++;
  return;
}

string CharList::toString() const
{
  cout<< " entered toString()"<<endl;
  string s= "";
  int length = CharList::size();
  CharListNode * traversal = header;
  cout << trailer->prev->element<<endl;
  cout << header->next->element<<endl;
  //cout<<header->next->next->element<<endl;
  for(int i=0; i < length; i++)
  {
    traversal = header -> next;
    char x = header->element;
    cout << x << endl;
    s = s+x;
  }
  cout<< s << endl;
  return s;
}

So for example the following piece of code :

CharList CharList_2 = CharList("abcd");
string word = CharList_2.toString();

is giving an exit status 1 error.

Aucun commentaire:

Enregistrer un commentaire