Search code examples
c++positionfindqueue

How to find an especific element on a queue?


I'm really newbie in c++, and now I'm trying to find a specific number in a queue, but it doesn't work, I'm getting this error:

  • Line 34 cannot convert 'node' to 'node*' in initialization.
  • Line 71 could not convert 'q' from 'node*' to 'node'.

what I'm doing is this:

#include <iostream>
using namespace std;

typedef struct node {
        int data;
        node * next;
        }queue;
        queue *Q, *first, *final=NULL;


void push()
{
     int number;    
     cout<<"Enter the number: ";
     cin>>number;
     Q=new node; 
     Q->data=number;
     Q->next=NULL;
     if(first==NULL)
     {
        final=first=Q;
     }
     else
     {
         final->next = Q;
         final = Q;    

     }
}

void findElement(node q ,int number)
{

     node * Q=q;
     int i=0,flag=0;

     while(Q!=NULL)
     {
        if(Q->data==number)
        {
           cout<<"Found in position: "<<i<<endl;
           flag=1;
        }
        Q=Q->next;
        i++;
     }
     if(flag==0)
     {
        cout<<"\n\nNot found..."<<endl;
     }
}

int main()
{
    int number,x;
    node *q=NULL;

    cout<<"1 Push"<<endl;
    cout<<"2 Find"<<endl;
    cin>>x;
    do
    {  
        switch (x)
        {
        case 1:
            push();
            break;
        case 2:
            cout<<"\n\nEnter the number you want to find: ";
            cin>>number;
            findElement(q,number);
            break;
        default:
            cout<<"Invalid option..."<<endl;
            break;

        }
    }while (x!=0); 
}

I know that my program might be really bad, but I'm trying really hard to learn, so please if you can tell me what I'm doing wrong it'd mean so much to me. Thanks in advance.


Solution

  • You may have other issues involved, but for those specific errors, you are trying to copy a node to a node*. The latter is a pointer.

    //This won't work.
    node * Q=q;
    
    // This will.  (However...)
    node* Q = &q;
    

    Similarly, on line 71

    findElement( q, number);
    

    q is of type node* (pointer to node), but findElement takes type node. Perhaps you should change findElement( node q, int number ) to findElement( node* q, int number )

    Pointers can take a while to wrap your head around, and the syntax is subtle. They are a key point to the language though.
    http://www.cplusplus.com/doc/tutorial/pointers/ http://www.tutorialspoint.com/cplusplus/cpp_pointers.htm