循环链表的实现

如下全部:

#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");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值