[英]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 列表中的节点之后 当我打印列表时 Output 是
1 2 3 4 5
在那之后当我将 11 12 13 14 15 添加到代码中时 output 来了
1 2 3 4 5 11 12 13 14 15
但我不想要以前的价值。 如何清除以前的列表以存储新值?
问题可能对前辈来说似乎很愚蠢但我是初学者。 所以请虚心帮助我。 我会很感激。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.