简体   繁体   中英

Printing A Circular Linked List

I am doing an Assignment which is about Creating and Printing a Circular Linked List.

Here is my Code:

#include <iostream>
#include <conio.h>
using namespace std;
class node
{

  public:
  int data;
  node *next;
  node() : data(0), next(NULL) {}
};

 class list
{ 
private:
node *first;
node *last;

public:
list() : first(NULL), last(NULL) {}
void add_last(int n)
{
    if (first == NULL)
    {
        first = new node;
        first->data = n;
        first->next = NULL;
        last = first;
    }
    else
    {
        node *ptr = new node;
        last->next = ptr;
        last = ptr;
        last->data = n;
        // cout<<last->data;
    }
}
void add_first(int n)
{
    if (first == NULL)
    {
        first = new node;
        first->data = n;
        first->next = NULL;
        last = first;
    }
    else
    {
        node *ptr = new node;
        ptr->data = n;
        ptr->next = first;
        first = ptr;
        last->next = ptr;
        // cout << last->data;
    }
}
void show()
{
    if (first == NULL)
    {
        cout << "List is Empty.";
        return;
    }
    else
    {
        node *ptr = first;
        while (ptr != last)
        {
            cout << ptr->data << " ";
            ptr = ptr->next;
        }
        cout << ptr->data << " ";
    }
   }

  };

 int main()
{
 list l;
 l.add_last(1);
 l.add_last(2);
 l.add_last(3);
 l.add_last(4);
 l.add_last(5);
 cout << "Contents of the List:\n";
 l.show();
 l.add_last(11);
 l.add_last(12);
 l.add_last(13);
 l.add_last(14);
 l.add_last(15);
 cout << "\nContents of the List:\n";
 l.show();


 return 0;
 }

After Adding 1 2 3 4 5 at last Nodes in list When I print the list then Output is

1 2 3 4 5

After That When I add 11 12 13 14 15 into code Then The output came is

1 2 3 4 5 11 12 13 14 15

But I do not want Previous value. How can I clear Previous List to store New values?

Question May be seems stupid To seniors But I am a beginner. So please Humbly Help me. I will be thankful.

You can call a deletelist method before displaying next added elements as follows:

void deleteList()
{

    node* current = first;
    node* next = NULL;
  
    while (current != NULL) 
    {
        next = current->next;
        delete(current);
        current = next;
    }
    first = NULL;
}

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM