循环链表的实现和操作

关于这个问题,你首先要明白?

1.什么是循环链表?

2.为什么要有循环链表?

3.与普通的线性链表相比,又有什么优点?

弄清楚这些问题,再来看代码,如下: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();
		void ins_linked_CList(T,T);
		int del_linked_CList(T);
};

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<<"Empty linked clist"<<endl;return;}
	do{
	cout<<p->d<<endl;
	p=p->next;
	}while(p!=head);
	return;
}

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;
}
还是以前的那个线性表例子不过稍微改一下即可,linked_CList_main.cpp

#include"linked_CList.h"
int main(){
	linked_CList<int> s;
	cout<<"1 ouput the element"<<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<<"2 ouput the element"<<endl;
	s.prt_linked_CList();
	if(s.del_linked_CList(30)) cout<<"delete:30"<<endl;
	else
		cout<<"there is no 30"<<endl;
	if(s.del_linked_CList(50)) cout<<"delete:50"<<endl;
	else
		cout<<"there is no 50"<<endl;
	cout<<"3 ouput the element"<<endl;
	s.prt_linked_CList();
	return 0;
}

最后说几句,其实循环链表就是简化了,线性表2种情况,为空和只有一个头结点,这样就统一到一起来了,因为它自己至少有一个表头结点,所以绝对不为空

还有插入一个元素,(10,10)就是说,在10结点前插入一个10,什么意思?就是空链表插入一个新结点它是10,当有这个以后,20,30都就可以方便的进行插入,

而(40,40)这个怎么理解呢?这个链表中根本没有40,而且和10,20,30都没有关系,那往哪里插入呢?因为它会找40的位置,从head就开始,一直到最后都没找到,所以就在这个链表最后一个结点10的后面插入了,否则,就循环到head结点了,看看实验结果和输出代码,好好理解一下,截图如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值