Sei sulla pagina 1di 3

Circular Linked List

#include <iostream>

using namespace std;

struct Node
{
int data;
Node *next;
};

Node *head = NULL;

void displayList()
{
if(head == NULL)
cout << "List is empty";
else
{
Node *t = head;

while(t->next != head)
{
cout << "Data: " << t->data << " at location " << t << endl;
t = t->next;
}
cout << "Data: " << t->data << " at location " << t << endl;
}
}

void deleteList()
{
if(head == NULL)
cout << " List is empty. Nothing to delete";
else
{
Node *t1 = head;
Node *t2 = NULL;

while(t1->next != head)
{
t2 = t1;
t1 = t1->next;
}
if(t2 == NULL)
{
head = NULL;
}
else
t2->next = head;
delete t1;
}
}

void appendList(int d)
{
Node *tmp = new Node;
tmp->data = d;
tmp->next = head;

if(head == NULL)
{
head = tmp;
tmp->next = head;
}
else
{
Node *t = head;

while(t->next != head)
{
t = t->next;
}
t->next = tmp;
}
}

int main()
{
int choice;
int d;
cout <<" ================================= " <<endl;
cout << "To append a number, press 1" <<endl;
cout << "To delete a number, press 2" <<endl;
cout << "To view the list, press 3" <<endl;
cout << "To exit the program, press 0" <<endl;
cout <<" ================================= " <<endl;
cout << "Now enter your choice: ";
cin >> choice;

do
{

switch(choice)
{
case 1:
cout << "Enter the number you want to add: ";
cin >> d;
appendList(d);
break;
case 2:
deleteList();
break;
case 3:
cout << endl << endl;
displayList();
cout << endl << endl;
break;

default:
cout << "Please enter a valid number" <<endl;
}
cout <<" ================================= " <<endl;
cout << "To append a number, press 1" <<endl;
cout << "To delete a number, press 2" <<endl;
cout << "To view the list, press 3" <<endl;
cout << "To exit the program, press 0" <<endl;
cout <<" ================================= " <<endl;
cout << "Now enter your choice: ";
cin >> choice;

}while(choice != 0);

return 0;
}

Potrebbero piacerti anche