Linked List with only Tail

Hello,
I'm trying to create circular Linked List, and I'm only allowed to use Tail pointer - no head pointer.

I have tried to modify my regular circular LL code (that has Head pointer), but so far I failed.

Can anyone offer some advice?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Queue::Queue() : myBack(0)
{

}

Queue::~Queue()
{
    Queue::NodePointer prev = myBack->next, ptr;

    while(prev != myBack)
    {
        ptr = prev->next;
        delete prev;
        prev = ptr;
    }
    delete prev;
}

bool Queue::empty() const
{
    return (myBack == 0);
}

void Queue::enqueue(const QueueElement & value)  //this seems to have problems
{
    Queue::NodePointer newptr = new Queue::Node(value);

    if(empty())
        myBack = newptr;
    else
    {
        newptr->next = myBack->next;
        myBack->next = newptr;
        myBack = newptr;
    }
}

void Queue::display(ostream & out) const
{
    Queue::NodePointer ptr;
    for (ptr = myBack->next; ptr != myBack; ptr = ptr->next)
        out << ptr->data << " ";
    out << endl;
}


This is how it's supposed to be:

http://s28.postimg.org/hihpi4cbx/Capture.png
Do you know what a Queue with a single entry will look like? Hint: where does newptr->next point?

That is the key to your enqueue function when the the queue is empty.
I'm guessing that when the queue is empty then I do what I'm already doing. But, when the queue has one element, that element's next points to that element again?
Then, when I insert 2nd element, things start to change as they should, and I always move myBack to the last place?
Right. The element's next must point to the element. You didn't do that in your code. That is probably why you are seeing a problem.
Thanks for your help. Managed to get it working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void Queue::enqueue(const QueueElement & value)
{
    //allocate memory for new element
    Queue::NodePointer newptr = new Queue::Node(value);

    //if list is empty, this is our only element, its NEXT points to itself
    if(empty())
    {
        myBack = newptr;
        myBack->next = myBack;
    }
    else
    {
        //new elements NEXT will point to current TOP
        newptr->next = myBack->next;
        //put new element after current myBack
        myBack->next = newptr;
        //change myBack so that it points to new "newest" element
        myBack = myBack->next;
    }
}
Topic archived. No new replies allowed.