c ++链表,插入字符串

时间:2017-03-09 06:18:30

标签: c++ list pointers linked-list

这是我的作业:创建一个链表类,它按字母顺序存储唯一(不允许重复)字符串列表。 enter image description here

这是我到目前为止所做的,但是没有用。谁能为我找到问题?非常感谢你。错误如下所示:

+       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> > >

我的代码:

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;
    }
}

1 个答案:

答案 0 :(得分:0)

您的while下方可能会遇到一些问题,因为每当您发现下一个节点的数据小于newNode时,就会插入newNode

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

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

我认为您的解决方案是找到小于newNode的最大节点的位置。您可以参考以下代码:

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

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