c++ - 使用类的 C++ 方法的链表

标签 c++ class linked-list

问题是,虽然在链表中添加数据没问题,但是当我们从列表中搜索内容时,它说列表是空的 但是如果我初始化这个

struct student * head = NULL;
struct student * curr = NULL; 

在课外它工作正常是我的方法正确还是我们不能这样做?

#include <iostream>

    using namespace std;

    struct student{
    int data = -100;
    student * next;
    };

    class linkedlist{
     struct student * head = NULL;
     struct student * curr = NULL;

    public:
    void insertitem()
    {
       if(head == NULL){
       struct student * temp = new student;
       head = temp;
       curr = temp;
       temp->next = NULL;
       cout << "Enter the data" << endl;
       cin >> temp->data;
    }
       else if(head != NULL){
           struct student * temp = new student;
           curr->next = temp;
           curr = temp;
           temp->next = NULL;
           cout << "Enter the data" << endl;
           cin >> temp->data;
       }
    }

    void searchitem(int x)
    {
        student * temp = new student;
        temp = head;
        if(temp != NULL)
        {

         while(temp->data != x)
          {
            temp = temp->next;  //Traversal

            if(temp == NULL){
                break;
             }

          }
        }
        if(temp != NULL)
        {
            cout << "found" << endl;
            cout << temp->data << endl;
        }

        else{
            cout << "Not found" << endl;
        }
    }

    };

    int main()
    {
      int x = -100;

      while(x != 0){
      cout << "--------------------" << endl;
      cout << "Enter 1 -- Insertion" << endl;
      cout << "Enter 0--- Terminate" << endl;
      cout << "--------------------" << endl;
      cin >> x;

      linkedlist l1;

      switch(x)
      {
      case 1:
           l1.insertitem();
        break;
      case 2:
           l1.searchitem(6);
        break;
      }
      }
        return 0;
    }

最佳答案

您在每次迭代时都创建了一个新的链表

将声明移出循环。

关于c++ - 使用类的 C++ 方法的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39727642/

相关文章:

c++ - 在另一个类中定义复杂(大型)类是否有任何开销?

c++ - 链表的几种实现——C++

Java - 向 LinkedList 提供对象时接收 NullPointerException

javascript - 在 IE6 中链接 CSS 类 - 试图找到一个 jQuery 解决方案?

c++ - 从另一个 cpp 更新文本框值

python - python3源代码的类图查看器应用程序

C Segmentation Fault(核心转储)与链表

c++ - isdigit() 在 C++ 中不应该更快吗?

c++ - 如何设置、清除和切换单个位?

c++ - 在不改变缩进的情况下重新格式化 C++ 大括号?