(單向)循環鏈表類

循環鏈表類:文件名:linked_CList.h

#include <iostream>
using namespace std;
template <class T>
struct node
{
	T d;
	node * next;
};
template <class T>
class linked_CList
{
private:
	node<T> *head; //循環表頭指針
public:
	linked_CList();
    void prt_linked_CList();
	//int flag_linked_CList();
	void ins_linked_CList(T,T);//在包含元素x的結點前面插入新元素b
	int del_linked_CList(T);//刪除包含元素x的結點
};
template <class T>
linked_CList<T>::linked_CList()
{
	node<T> *p;
	p=new node<T>;
	p->d=0;
	p->next=p;
	head=p;
	return;
}
template<class T>
void linked_CList<T>::prt_linked_CList()
{
	node<T> *p;
	p=head->next;
	if(p==head)
	{
		cout<<"空的循環鏈表:"<<endl;
		return;
	}
	do 
	{
		cout<<p->d<<endl;
		p=p->next;
	} while (p!=head);
	return;
}
//在包含元素x的結點前插入新元素b
template<class T>
void linked_CList<T>::ins_linked_CList(T x,T b)
{
	node <T> *p,*q;
	p=new node<T>;
	p->d=b;
	q=head;
	while((q->next!=head)&&((q->next)->d)!=x)
	{
		q=q->next;
	}
	p->next=q->next;
	q->next=p;
	return;
}
template<class T>
int linked_CList<T>::del_linked_CList(T x)
{
	node<T> *p,*q;
	q=head;
	while((q->next!=head)&&(((q->next)->d)!=x))
		q=q->next;
	if(q->next==head)
		return 0;
	p=q->next;
	q->next=p->next;
	delete p;
	return 1;

}


應用實例:

#include "linked_Clist.h"
#include <stdlib.h>
int main()
{
 linked_CList<int> s;
 cout<<"第一次掃描輸出循環鏈表s中的元素:"<<endl;
 s.prt_linked_CList();
 s.ins_linked_CList(10,10);
 s.ins_linked_CList(10,20);
 s.ins_linked_CList(10,30);
 s.ins_linked_CList(40,40);
 cout<<"第二次掃描輸出循環鏈表s中的元素:"<<endl;
 s.prt_linked_CList();
 if(s.del_linked_CList(30))
  cout<<"刪除元素:30"<<endl;
 else
  cout<<"循環鏈表中沒有元素30"<<endl;
 if(s.del_linked_CList(50))
  cout<<"刪除元素:50"<<endl;
 else
  cout<<"循環鏈表中沒有元素50"<<endl;
 cout<<"第3次掃描輸出循環鏈表s中的元素:"<<endl;
 s.prt_linked_CList();
 system("pause");
 return 0;

}

實驗結果:

 

發佈了56 篇原創文章 · 獲贊 21 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章