Search code examples
c++data-structureslinked-listqueuecircular-list

Printing the Circular linked list


#include <iostream>
#include <cstdlib>

using namespace std;

struct node
{
    int data;
    struct node* link;
};

struct node* front;
struct node* rear;

void insert()
{
    struct node*temp;
    temp = (struct node*)malloc(sizeof(struct node));
    cin >> temp->data;
    if (front == NULL)
    {
        front = rear = temp;
    }
    else
    {
        rear->link = temp;
        rear = rear->link;
    }
    rear->link = front;
}


void del()
{
    struct node* temp;
    temp = front;
    if (front == NULL)
        cout << "Underflow";
    else
    {
        front = front->link;
        free(temp);
    }
    rear->link = front;
}

void disp()
{
    struct node* temp;
    temp = front;
    if (front == NULL)
        cout << "Empty";
    else
    {
        do
        {
            cout << temp->data << "->";
            temp = temp->link;
        } while (temp != front);

    }
    rear->link = front;
}
int main()
{
    int n;
    bool run = true;
    while (run)
    {
        cin >> n;
        switch (n)
        {
        case 1:
            insert();
            break;
        case 2:
            del();
            break;
        case 3:
            disp();
            break;
        case 4:
            run = false;
            break;
        }
    }
    return 0;
}

I am new to the concept.I wrote a code for insertion deletion and display of elements using queue implementing the concept of linked list..The program is working fine without any errors . But when the output is displayed . I need to display the output along with the first element I inserted..E.g: My input is 1 2 1 3 1 4 3 The output is 2->3->4->

but the output I need is 2->3->4->2-> I want to see the first element again at the last


Solution

  • All you have to do is just adding a single line after the do-while loop as follows:

    do
    {
        cout << temp->data << "->";
        temp = temp->link;
    } while (temp != front);
    cout<< front->data << "->";
    

    assuming front is the head of your linked-list. Now I've a question for you, what you gonna do if there is a single entry? Since it is going to be displayed twice.