数据结构-双向循环链表

数据结构-双向循环链表:

长相:


#include <iostream>
using namespace std;
template <typename T>
struct DoubleList
{
	T data;
	struct DoubleList<T>* front;
	struct DoubleList<T>* tail;
	struct DoubleList<T>* CreateList()
	{
		//要内存 
		struct DoubleList<T>* List = new DoubleList<T>; //很容易犯错
		//描述最初状态
		List->front = List->tail = List;
		return List;
	}
	struct DoubleList<T>* CreateNode(T data)
	{
		//要内存 
		struct DoubleList<T>* Node = new DoubleList<T>; //很容易犯错
		//描述最初状态
		//方便连接
		Node->front = Node->tail = NULL;
		Node->data = data;
		return Node;
	}

	void InsertHeadOrTail(struct DoubleList<T>* List, T data)
	{
		//首先创建插入的结点
		struct DoubleList<T>* Node = CreateNode(data);
		struct DoubleList<T>* p = List;
		while (p->tail != List)
		{
			p = p->tail;
		}
		//看图写作文
		List->front = Node;
		Node->tail = List;
		Node->front = p;
		p->tail = Node;

	}
	bool IsEmptyList(struct DoubleList<T>* List)
	{
		return List->tail == List;  //1表示空
	}
	void PrintList(struct DoubleList<T>* List)
	{
		if (IsEmptyList(List))
		{
			cout << "表为空,无法打印" << endl;
			return;
		}
		struct DoubleList<T>* p = List->tail;
		while (p->front != List->front)//面试题: 如何判链表是否循环
		{
			cout << p->data << "\t";
			p = p->tail;
		}
		cout << endl;
	}

	void InsertNodeAppoin(struct DoubleList<T>* List, T data, T item)
	{
		struct DoubleList<T>* Node = CreateNode(data);
		struct DoubleList<T>* p = List;
		struct DoubleList<T>* q = List->tail;
		while (q->data != item)
		{
			p = q;
			q = p->tail;
			if (p->tail == List)
			{
				cout << "未找到指定位置" << endl;
				return;
			}
		}
		p->tail = Node;
		Node->front = p;
		Node->tail = q;
		q->front = Node;
	}
	void DeleteListTail(DoubleList<T>* List)
	{
		if (IsEmptyList(List))
		{
			cout << "链表为空无法删除" << endl;
			return;
		}
		DoubleList<T>* p = List;
		DoubleList<T>* q = List->tail;
		while (q->tail != List)
		{
			p = q;
			q = p->tail;
		}
		List->front =p;
		p->tail = List;
		delete q;
	}
	void DeleteListAppoin(DoubleList<T>* List, T item)
	{
		if (IsEmptyList(List))
		{
			cout << "链表为空无法删除" << endl;
			return;
		}
		DoubleList<T>* p = List;
		DoubleList<T>* q = List->tail;
		while (q->data != item)
		{
			p = q;
			q = p->tail;
			if (p->tail == List)
			{
				cout << "未找到指定位置" << endl;
				return;
			}
		}
		p->tail = q->tail;
		q->tail->front = p;
		delete q;
	}


};




int main()
{
	struct DoubleList<int> myList;
	DoubleList<int> * List=myList.CreateList();
	myList.InsertHeadOrTail(List, 1);
	myList.InsertHeadOrTail(List, 2);
	myList.InsertHeadOrTail(List, 3);
	myList.InsertHeadOrTail(List, 5);
	myList.InsertNodeAppoin(List, 4,5);
	myList.PrintList(List);

	cout << "尾删除" << endl;
	myList.DeleteListTail(List);
	myList.PrintList(List);

	cout << "指定位置删除" << endl;
	myList.DeleteListAppoin(List, 2);
	myList.PrintList(List);
	system("pause");

	return 0;
}


猜你喜欢

转载自blog.csdn.net/ydpawx/article/details/78023702