2019《王道数据结构》算法题-循环链表C++实现

#include<iostream>
using namespace std;
template<class T> 
struct Node{
	T data;
	Node<T>* next;
	Node(Node<T>* n = NULL)
	{
		next = n;
		
	}
	Node(const T& item , Node<T>* n = NULL)
	{
		data = item;
		next = n;
	}
};
template<class T>
class CirList{//循环链表 
	public:
		CirList(){ 
			head = current = new Node<T>();
			head->next = head;
			count = 0;
		}
		~CirList(){
			Node<T>* q;
			while(head->next != head){
				q = head->next;
				head->next = q->next;
				delete q; 
				count--;
			}
		}
		int length() const
		{
			return count;
		}
		Node<T>*& getHead()
		{
			return head;
		}
		T get(int index){
			if(index > count - 1 || index < -1){
				cerr << "索引越界!" << endl;
				exit(1);
			}
			Node<T>* temp = head->next;
			for(int i = 0; i < index; i++){
				temp = temp->next;
			}
			return temp->data;
		}
		bool insert(int index , T x){
			if(index > count || index < -1){
				cerr << "索引越界!" << endl;
				return false;
			}
			Node<T>* temp = head;
			if(index != 0){
				temp = head->next;
				for(int i = 0; i < index-1; i++){
					temp = temp->next;
				}
			}
			temp->next = new Node<T>(x,temp->next);
			count++;
			return true;
		}
		bool add(T x){
			return insert(count,x);
		}
		void print() const
		{
			Node<T>* temp = head->next;
			
			while(temp != head){
				cout << temp->data << " ";
				temp = temp->next;
			}
		} 
		template<class X>
		static void print1(Node<X>* a){
			Node<X>* temp = a;
			while(temp != a){
				cout << temp->data << " ";
				temp = temp->next;
			}
		}
		template<class X>
		static void print2(Node<X>* a){
			Node<X>* temp = a->next;
			while(temp != a){
				cout << temp->data << " ";
				temp = temp->next;
			}
		}
	private:
		Node<T>* head;
		Node<T>* current;
		int count;
	public:
		template<class X>
		static void link(Node<X>* h1 , Node<X>* h2)
		{//2.3.7.18将循环单链表h2连接到h1之后。 
			Node<X>* temp = h1;
			while(temp->next != h1)
				temp = temp->next;
			temp->next = h2->next;
			while(temp->next != h2)
				temp = temp->next;
			temp->next = h1;
		}
		void deleteMin()
		{//2.3.7.19反复找出单链表中结点值最小的结点并输出,然后将该结点从中删除,直到单链表空为止,再删除表头结点。 
			Node<T>* pre = head;
			Node<T>* min = head->next;
			Node<T>* temp = min->next;
			Node<T>* p_temp = min;
			while(head->next != head){
				if(temp == head){
					cout << min->data << endl;
					pre->next = min->next;
					delete min;
					pre = head;
					min = head->next;
					temp = min->next;
					p_temp = min;
					count--;
					continue;
				}
				if(temp->data < min->data){
					pre = p_temp;
					min = temp;
				}
				temp = temp->next;
				p_temp = p_temp->next;
			}
			//delete head;
		}
	/*
		***************************END*************************** 
	*/
	/*
		**********************作者QQ632660120 *******************
	*/ 
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值