如下全部:
#include<iostream>
using namespace std;
class Node
{
public:
Node *next;
int data;
};
class circleList{
public:
circleList()
{
head = new Node();
head->next = head;
head->data = 0;
length = 0;
}
~circleList()
{
Node* ptr1 = head;
Node* ptr2 = head;
while (ptr2->next != NULL)
{
ptr2 = ptr2->next;
delete ptr1;
ptr1 = ptr2;
}
delete ptr2;
delete ptr1;
delete head;
ptr2 = nullptr;
ptr1 = nullptr;
head = nullptr;
}
void createCircleList(int n);
void displayNode();
void deleteNode(int n);
void insertNode(int n, int data);
int getLength();
bool isEmpty();
private:
Node* head;
int length;
};
void circleList::createCircleList(int n)
{
if (n<0)
{
cout << "wrong length " << endl;
}
else
{
length = n;
printf("please input the data you want to save:");
Node *p, *q;
p = head;
while (n--)
{
q = new Node;
cin >> q->data;
p->next = q;
q->next = head;
p = q;
}
}
}
void circleList::displayNode()
{
Node *p;
p = head->next;
while (p != head)
{
cout<<p->data;
p = p->next;
}
cout << endl;
}
void circleList::deleteNode(int n)
{
if (n<0 || n>length)
{
cout << "wrong positon" << endl;
return;
}
else
{
Node *p, *q;
p = head;
for (int i = 1; i < n; i++)
p = p->next;
q = p->next;
p->next = q->next;
delete q;
q = NULL;
}
}
void circleList::insertNode(int n, int data)
{
Node *q, *p = new Node();
p->data = data;
q = head;
for (int i = 1; i<n; i++)
q = q->next;
p->next = q->next;
q->next = p;
}
int circleList::getLength()
{
return length;
}
bool circleList::isEmpty()
{
return head == head->next;
}
void main()
{
circleList Clist;
Clist.createCircleList(5);
Clist.displayNode();
Clist.deleteNode(4);
Clist.displayNode();
Clist.insertNode(2, 4);
Clist.insertNode(3, 6);
Clist.displayNode();
system("pause");
}