使用c++方法的链表类



问题是,虽然在链表中添加数据很好,但当我们从列表中搜索一些东西时,它说列表是空的但是如果我初始化这个

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

在每次迭代中创建一个新的linkedlist

相关内容

  • 没有找到相关文章

最新更新