M Ahmad Rana
M Ahmad Rana

Reputation: 33

Linked list using the c++ approach of classes

The problem is that while adding data in the linked list its fine but when we search something from the list it says the list is empty But if I initialize this

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

outside the class then it works fine is my approach correct or we can not do it this way?

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

Upvotes: 0

Views: 296

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

You're creating a new linkedlist on every iteration.

Move the declaration out of the loop.

Upvotes: 1

Related Questions