单向循环链表的C++实现

单向循环链表的C++实现

 

        单向循环链表与单向链表相比,其尾结点的下一个结点指向首元素,这样就构成了一个环:

 

 

        单向循环链表的结点定义,与单向链表的结点定义一致:

#ifndef SIMPLENODE_HPP
#define SIMPLENODE_HPP
template<typename T>         //定义一个模板T  写单链表 
class SingleNode
{
public:
	T element;     
	SingleNode* next;
	SingleNode(const T& theElement,SingleNode* nextone=NULL)
	           :element(theElement),next(nextone) {}   
};
#endif


        当把各结点串起来组合成一个单向循环链表后,就需要添加对应的实现:

        1.定义这个单向链表类的构造函数及析构函数

        2.清空链表内所有元素

        3.给出元素位置再返回对应结点

        4.返回链表内部元素个数

        5.判断这个链表是否为空

        6.返回链表首尾的元素值

        7.查找元素是否在此链表内,如果在则返回所在位置

        8.从首端到尾端输出链表上的各元素

        9.对链表插入元素以及删除元素

 

        对应的类框架如下:

#ifndef CIRCLESINGLELINKLIST_HPP
#define CIRCLESINGLELINKLIST_HPP
#include<iostream>
#include"simplenode.hpp"
//这里默认位置pos的开始是从1开始,而不是从0开始 
template<class T>
class CircleSingleLinkList          //单链表类的定义
{
private:
	SingleNode<T>* head;           //链表头指针
	SingleNode<T>* tail;           //链表尾指针
	int size;             //元素个数
	SingleNode<T>* GetPointAt(int pos) 
	{...}
public:
	CircleSingleLinkList():head(),tail(),size(0) {}
	~CircleSingleLinkList() {Clear();}
	void Clear()
	{...}
	int Size() {...}        //返回元素个数
	bool isempty()  {...}  //返回链表是否为空 
	//-----------------------------------------------------
	//这里添加元素
	//------在尾部添加元素
	void AddBack(T val)
	{
		SingleNode<T>* pNode=new SingleNode<T>(val);
		if (isempty())   //链表为空时 
		{...}
		else
		{...}
		size++;
	} 
	//------在指定位置插入元素
	bool AddAt(T val,int pos)
	{
		SingleNode<T>* pNode=NULL;
		if (pos<=0 || pos>size)
		{...}
		if (pos==size)       //在尾部插入元素     
			AddBack(val);
		else if (pos==1)      //在头部插入元素 
		{...}
		else
		{...}
		size++;
		return true;
	} 
	//-----------------------------------------------
	//这里删除元素 
	bool RemoveBack()         //删除尾部元素
	{
		return RemoveAt(size);    
	} 
	bool RemoveAt(int pos)      //删除指定位置元素
	{
		SingleNode<T>* pNode=NULL;
		if (isempty())
		{...}
		if (pos<=0 || pos>size)
		{...}
		if (size==1)       //只有1个元素时相当于清空链表
		{
			Clear();
		} 
		if (pos==1)        //并且size!=1, 删除头部元素时 
		{...} 
		else if (pos==size)
		{...}
		else
		{...}
		size--;
		return true;
	} 
	//---------------------------------------
	T GetHeadVal()
	{...}
	T GetTailVal()
	{...}
	int Find(T val)      //查找元素
	{...}
	void ShowAllVal()    //从头到尾输出链表上的元素 
	{...} 
}; 
#endif


        给出类框架后,就该一个个给出对应的实现了。除了部分细节需要修改,其他的与单向链表的实现毫无二致:

        1.构造函数与析构函数:

	CircleSingleLinkList():head(),tail(),size(0) {}
	~CircleSingleLinkList() {Clear();}

        2.清空链表内所有元素:

	void Clear()
	{
		//从链表头到链表尾的方式逐个删除 
		const int nums=Size();
		if (!isempty())
		{
			for (int k=1;k<=nums;++k)
			{
				SingleNode<T>* temp=head->next;
				delete head;
				head=temp;
				size--;
			}
		}
		//如果链表本来就为空,就没必要再进for循环了 
	}

 

        3.给出元素位置再返回对应结点:

	SingleNode<T>* GetPointAt(int pos) 
	{
		SingleNode<T>* pNode=NULL;
		if (pos<=0 || pos>size)
			std::cout<<"out of range."<<std::endl;   //链表当前位置越界,异常
		else
		{
			pNode=head;            //当前位置满足条件,则一开始在链表头			
			for (int i=1;i<=pos-1;++i)   
				pNode=pNode->next;
		} 
		return pNode;
	}

        要注意的是,遍历元素位置时避免pNode所获得的值越界,队首元素进不了for循环,改变不了pNode;队尾元素如果设置成i=1;i<=pos;++i,pNode会读取队尾的下一个值,那个值越界。最后就会返回一个未定义的元素。

        4.返回首尾端元素、查找元素、输出所有元素、返回元素个数、判断列表是否为空:

	T GetHeadVal()
	{
		if (isempty())
		{
			std::cout<<"the link list is empty"<<std::endl;
			return NULL;   //return NULL
		}
		return head->element;
	}
	T GetTailVal()
	{
		if (isempty())
		{
			std::cout<<"the link list is empty"<<std::endl;
			return NULL;   //return NULL
		}
		return tail->element;
	}
	int Find(T val)      //查找元素
	{
		int pos=1;          //从起始位置1号位开始
		SingleNode<T>* findNode=head;
		do
		{
			if (findNode->element==val)
				return pos;
			findNode=findNode->next;
			pos++;
		}
		while (findNode!=head);
		std::cout<<"we can't find it,return -1"<<std::endl;
		return -1;
	}
	void ShowAllVal()    //从头到尾输出链表上的元素 
	{
		SingleNode<T>* findNode=head;
		do
		{
			std::cout<<findNode->element<<" ";
			findNode=findNode->next;
		}
		while (findNode!=head);
		std::cout<<"最后一个元素的下一个元素是"<<findNode->element<<std::endl; 
		std::cout<<std::endl; 
	} 
	int Size() {return size;}        //返回元素个数
	bool isempty()  {return size==0?true:false; }  //返回链表是否为空 

        由于此时,链表已成环状,所以要用一个循环进行控制,如果满足条件或者已经遍历一圈,要注意跳出,以免陷入死循环。

        5.链表中加入元素:

        这里也分四种情况讨论:

                ①插入元素位置越界                               

                ②在尾部插入元素                                   

                ③在头部插入元素                           

                ④在其他位置插入元素                   

        若插入元素成功,记得元素个数+1。这里用图示例空链表插入元素以及非空链表其他位置插入元素,其他情况读者们可以自己试着画图:

 


        代码如下:

 

	//这里添加元素
	//------在尾部添加元素
	void AddBack(T val)
	{
		SingleNode<T>* pNode=new SingleNode<T>(val);
		if (isempty())   //链表为空时 
		{
			head=pNode; tail=pNode; 
			tail->next=head;
		}
		else
		{
			tail->next=pNode;      
			tail=pNode;
			tail->next=head;
		}
		size++;
	} 
	//------在指定位置插入元素
	bool AddAt(T val,int pos)
	{
		SingleNode<T>* pNode=NULL;
		if (pos<=0 || pos>size)
		{
			std::cout<<"out of range."<<std::endl;
			return false;
		}
		if (pos==size)       //在尾部插入元素     
			AddBack(val);
		else if (pos==1)      //在头部插入元素 
		{
			pNode=new SingleNode<T>(val);
			pNode->next=head;
			head=pNode;
			tail->next=head;
		}
		else
		{
			//返回插入位置前面一个的位置指针 
			SingleNode<T>* pNode=GetPointAt(pos-1);  
			SingleNode<T>* newNode=new SingleNode<T>(val);
			newNode->next=pNode->next;
			pNode->next=newNode;
		}
		size++;
		return true;
	} 


        6.链表中删除元素:

        这里也分五种情况讨论:

                ①链表为空                                

                ②删除元素位置越界                               

                ③在尾部删除元素

                ④在头部删除元素

                ⑤在其他位置删除元素

        若删除元素成功,记得元素个数-1。这里没给出图示例,读者们可以自己试着画图

        代码如下:

 

	//这里删除元素 
	bool RemoveBack()         //删除尾部元素
	{
		return RemoveAt(size);    
	} 
	bool RemoveAt(int pos)      //删除指定位置元素
	{
		SingleNode<T>* pNode=NULL;
		if (isempty())
		{
			std::cout<<"the link list is empty"<<std::endl;
			return false;
		}
		if (pos<=0 || pos>size)
		{
			std::cout<<"out of range."<<std::endl;
			return false;
		}
		if (size==1)       //只有1个元素时相当于清空链表
		{
			Clear();
		} 
		if (pos==1)        //并且size!=1, 删除头部元素时 
		{
			pNode=head;
			head=head->next;
			tail->next=head;
			delete pNode;
		} 
		else if (pos==size)
		{
			SingleNode<T>* pPreNode=GetPointAt(pos-1);
			pNode=pPreNode->next;
			pPreNode->next=pNode->next;
			delete pNode;
			tail=pPreNode;
			tail->next=head;
		}
		else
		{
			SingleNode<T>* pPreNode=GetPointAt(pos-1);
			pNode=pPreNode->next;
			pPreNode->next=pNode->next;
			delete pNode;
		}
		size--;
		return true;
	} 


        最后,将上述实现放入之前所说的类框架后,就完成任务了。

 

 

 

 

参考文献:

1.《算法导论》2nd   Thomas H.Cormen , Charles E.Leiserson , Ronald L.Rivest , Cliford Stein 著,潘金贵、顾铁成、李成法、叶懋译
2.《数据结构与算法分析 C++描述》 第3版  Mark Allen Weiss著,张怀勇等译
3.《C++标准模板库 -自修教程及参考手册-》  Nicolai M.Josuttis著,侯捷/孟岩译

4.http://blog.csdn.net/mourinho_my_idol/article/details/12570609

 

  • 5
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解答这个问题。 首先,让我们来了解一下约瑟夫问题的背景。约瑟夫问题是一个经典的问题,据传是由古代历史学家约瑟夫斯(Josephus)提出的。问题的具体描述如下: 有n个人围成一圈,从第一个人开始报数,报到m的人出圈,剩下的人继续从1开始报数,直到剩下最后一个人。求出最后一个出圈的人的编号。 为了解决这个问题,我们可以使用单向循环链表实现。下面是一个简单的C++单向循环链表实现,包含了三个文件:Node.h、List.h和List.cpp。 首先是Node.h文件,用来定义节点类: ```cpp // Node.h #ifndef NODE_H #define NODE_H class Node { public: int data; Node* next; Node(int data) { this->data = data; next = nullptr; } }; #endif ``` 然后是List.h文件,用来定义链表类: ```cpp // List.h #ifndef LIST_H #define LIST_H #include "Node.h" class List { public: List(); ~List(); void insert(int data); void remove(Node* node); Node* getHead(); Node* getNext(Node* node); private: Node* head; }; #endif ``` 最后是List.cpp文件,用来实现链表类的方法: ```cpp // List.cpp #include "List.h" List::List() { head = nullptr; } List::~List() { Node* curr = head; while (curr != nullptr) { Node* temp = curr; curr = curr->next; delete temp; } } void List::insert(int data) { Node* node = new Node(data); if (head == nullptr) { head = node; head->next = head; } else { Node* curr = head; while (curr->next != head) { curr = curr->next; } curr->next = node; node->next = head; } } void List::remove(Node* node) { Node* curr = head; if (node == head) { head = head->next; } else { while (curr->next != node) { curr = curr->next; } curr->next = node->next; } delete node; } Node* List::getHead() { return head; } Node* List::getNext(Node* node) { return node->next; } ``` 现在我们就可以使用这个单向循环链表来解决约瑟夫问题了。下面是一个简单的解决方案: ```cpp #include <iostream> #include "List.h" int josephus(int n, int m) { List list; for (int i = 1; i <= n; i++) { list.insert(i); } Node* curr = list.getHead(); while (n > 1) { for (int i = 1; i < m; i++) { curr = list.getNext(curr); } Node* temp = curr; curr = list.getNext(curr); list.remove(temp); n--; } return list.getHead()->data; } int main() { int n = 5; int m = 3; int result = josephus(n, m); std::cout << "The last person is " << result << std::endl; return 0; } ``` 这个程序将输出: ``` The last person is 4 ``` 这就是使用C++单向循环链表解决约瑟夫问题的一个简单的例子。希望能对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值