c++ - 崩溃,同时打印链表的内容

标签 c++ linked-list

我在打印链接列表的内容时遇到了一些问题。我正在使用我在某处找到的示例代码。我确实对其进行了一些编辑,但我不认为这就是它崩溃的原因。

class stringlist 
{
  struct node 
  {
    std::string data;
    node* next;
  };
  node* head;
  node* tail;
public:
  BOOLEAN append(std::string newdata)
  {
      if (head)
      {
          tail->next = new node;
          if (tail->next != NULL)
          {
              tail=tail->next;
              tail->data = newdata;
              return TRUE;
          }
          else
              return FALSE;
      }
      else
      {
          head = new node;
          if (head != NULL)
          {
              tail = head;
              head->data = newdata;
              return TRUE;
          }
          else
              return FALSE;
      }
  }
  BOOLEAN clear(std::string deldata)
  {
      node* temp1 = head;
      node* temp2 = NULL;
      BOOLEAN result = FALSE;
      while (temp1 != NULL)
      {
          if (temp1->data == deldata)
          {
              if (temp1 == head)
                  head=temp1->next;
              if (temp1==tail)
                  tail = temp2;
              if (temp2 != NULL)
                  temp2->next = temp1->next;
              delete temp1;
              if (temp2 == NULL)
                  temp1 = head;
              else
                  temp1 = temp2->next;
              result = TRUE;
          }
          else // temp1->data != deldata
          {
              temp2 = temp1;
              temp1 = temp1->next;
          }
      }
      return result;
  }
  BOOLEAN exists(std::string finddata)
  {
      node* temp = head;
      BOOLEAN found = FALSE;
      while (temp != NULL && !found)
      {
          if (temp->data == finddata)
              found=true;
          else
              temp = temp->next;
      }
      return found;
  }
  void print()
  {
      node* tmp = head;
      while (tmp)
      {
          printf("%s", tmp->data.c_str());
          tmp = tmp->next;
      }
  }
  stringlist()
  {
      head=NULL;
      tail=NULL;      
  }
};

我的 main() 函数非常简单:

int main()
{
stringlist mylist;
  if (mylist.append("something"))
      count++;
  if (mylist.append("else"))
      count++;
  if (mylist.append("yet"))
      count++;
  cout<<"Added "<<count<<" items\n";
  mylist.print();
return 0;
}

出于某种原因,在 Print() 中 tmp 永远不会为 NULL

最佳答案

在节点中,在null旁边添加一个构造函数来初始化

关于c++ - 崩溃,同时打印链表的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2135355/

相关文章:

c++ - NULL检查qt中的整数

c++ - 了解 Valgrind 输出

c - 排序链表时出现段错误

java - 如何建立一个链表,每个节点都会有一个随机的int值,但是总值sum和节点数会预先固定?

c - C 中的数据结构指针处理

c - 附加到链表 C

C++ 将 'this' 指针传递给基类然后将其存储为子类的另一个基类的预期行为是什么

java - Java 和 C++ 的编码风格之间有什么具体区别?

c - 链表中的入队函数

c++ - 使用套接字编程的c++中的stringstream vs ifstream(ofstream)