打印循环链表

Printing A Circular Linked List

我正在做一个关于创建和打印循环链表的作业。

这是我的代码:

#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;
 }

最后在列表中添加 1 2 3 4 5 节点之后 当我打印列表时 那么输出是

1 2 3 4 5

在那之后当我将 11 12 13 14 15 添加到代码中时 然后输出是

1 2 3 4 5 11 12 13 14 15

但我不想要以前的值。 如何清除以前的列表以存储新值?

问题对老年人来说可能看起来很愚蠢 但我是初学者。 所以请虚心帮助我。 我会很感激的。

您可以在显示下一个添加的元素之前调用 deletelist 方法,如下所示:

void deleteList()
{

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