c++ queue implementation not working as expected

Benjamin Jones

Today I am looking to make my own dequeue in c ++ using pointers. Well, in the program, I want to create two dequeues in which to add different elements. Unfortunately, this is not what happened. On screen i got 6 5 insted only 6. Why?I'm not sure exactly how to make two separate dequeues? I think one of my problems are *L = NULL, * R = NULL but i am not sure? So my code so far -

#include <iostream>

struct elem
{
    int key;
    elem* next;
}*L = NULL, * R = NULL;

void push_l(int n, elem*& p)
{
    p = L;
    L = new elem;
    L->key = n;
    L->next = p;

    if (R == NULL)
        R = L;
}

int pop_l(int& n, elem*& p)
{
    if (L)
    {
        p = L;
        n = L->key;
        L = L->next;

        if (L == NULL)
            R = NULL;
        delete p;

        return 1;
    }
    else
    {
        return 0;
    }
}



int main()
{
    int k;
    elem* p = new elem;
    elem* q = new elem;
    push_l(5, p);
    push_l(6, q);

    while (pop_l(k, q))
    {
        std::cout << k<< " ";
    }
}

I am not sure how can i print only 6 on the screen because this element is only pushed to the dequeue ? Also these are just some of the features for dequeue because I want to understand it from the beginning !

Aconcagua

Such a class might look like this:

class /* or struct, if you really want to... */ Dequeue 
{
public:
   void push(int value);
   bool pop(int& value); // if you return 1 for success and 0 for error
                         // bool is the more appropriate type...

private:
   struct elem // it's an implementation detail, so recommendable
               // to have it as a nested class...
   {
        // just as you had before...

        // you might additionally provide a constructor:
        // this makes creating new instances easier/simpler
        elem(int k, elem* n) : key(k), next(n) { }
   };

   elem* m_head = nullptr;
   elem* m_tail = nullptr; 
}

void Dequeue::push(int value)
{
//   auto tmp = new elem;
//   tmp->key = value;
//   tmp->next = m_head;
//   m_head = tmp;

// with constructor:
   m_head = new elem(value, m_head);

   if(!m_tail)
       m_tail = m_head;
}

bool Dequeue::pop(int& value)
{
   // transform analogously using m_head and m_tail instead of L and R
   // return true and false instead of 1 and 0 
}

You'll notice that the function looks just as before – however as now a member function, it accesses the class member of the instance upon which the function is called:

Dequeue d1; 
Dequeue d2;
// each of these have their own, separate m_head and m_tail pointers!

d1.push(12);
d2.push(10);
// now pushed to separate instances 

Side note: untested code, if you find a bug, please fix yourself...

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related