简体   繁体   中英

c++ linked list, insert strings

This is my homework: Create a linked list class which stores a list of unique (no duplicates allowed) strings in alphabetic order. enter image description here

and this is what I have so far, which is not working. can anyone find the problems for me? thank you very much. the error looks like this:

+       std::_String_alloc<std::_String_base_types<char,std::allocator<char> > >    {_Mypair={_Myval2={_Bx={_Buf=0x0135f988 "Adam" _Ptr=0x6d616441 <Error reading characters of string.> ...} ...} } }  std::_String_alloc<std::_String_base_types<char,std::allocator<char> > >

my code:

bool LinkedList::insert(string dataInsert) { 

     //remember to use find funcion to check dupcated.
    if (find(dataInsert) != 0)
        return false;

     // build new node.
    Node* newNode = new Node;
    newNode->data = dataInsert;
    newNode->next = NULL;

    //insert into empty list
    if (head == NULL) 
    {
        head = newNode;
        return true;
    }

    //insert before first item
    if (newNode->data < head->data)
    {
        newNode->next = head;
        head = newNode;
        return true;
    }

    //insert somewhere after first item
    Node* previous = head;
    while (previous->next != NULL && previous->next->data < newNode->data)
    {
        previous = previous->next;

        newNode->next = previous->next;
        previous->next = newNode;
        return true;
    }
}

Your below while might have some problems because newNode was inserted every time when you found the next node has smaller data than newNode .

while (previous->next != NULL && previous->next->data < newNode->data)
{
   previous = previous->next;

   newNode->next = previous->next;
   previous->next = newNode;
   return true;
}

I think your solution is finding a position of the largest node that smaller than newNode . You can refer below code:

 while (previous->next != NULL && previous->next->data < newNode->data)
 {
    previous = previous->next;     
 }

 newNode->next = previous->next;
 previous->next = newNode;
 return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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