循环双向链表(C++)

这是一个带有 空头结点空尾结点 的循环双向链表c++实现

#include

using namespace std;

class DoubleLinkedList {
	private:
		struct Node {
			int data;
			Node* pre;
			Node* next;
		};
		Node* head = new Node;
		Node* last = new Node;

	public:
		DoubleLinkedList() {
			head->pre  = last;
			head->data = NULL;
			head->next = last;
			last->pre  = head;
			last->data = NULL;
			last->next = head;
		}
		~DoubleLinkedList() {
			Node* now = head;
			Node* temp = nullptr;
			while (now != last) {
				temp = now;
				now = now->next;
				last->next = now;
				now->pre = nullptr;
				delete temp;
				temp = nullptr;
			}
			delete last;
			last = nullptr;
		}

		//新建结点
		Node* CreateNode(int value) {
			Node* newNode = new Node;
			newNode->data = value;
			return newNode;
		}

		//插入数据(尾插)
		void insertNode(int value) {
			Node* newNode = CreateNode(value);
			//当创建第一个结点时
			if (head->next == last) {
				newNode->pre  = head;
				newNode->next = last;
				head->next = newNode;
				last->pre  = newNode;
			} else {//当创建的结点不是第一个结点时
				Node* temp = head;
				while (temp->next != last) {
					temp = temp->next;
				}
				temp->next = newNode;
				newNode->pre = temp;
				newNode->next =	last;
				last->pre = newNode;
			}
		}

		//删除数据(按索引删除)
		//参数:结点索引值(从0开始)
		void DeleteNodeByIndex(int num) {
			if (head->next == last) {
				cout << "该表为空,不可再删除!!" << endl;
				return;
			}
			//删除[0]时
			if (num == 0) {
				Node* temp = head->next;
				head->next = temp->next;
				temp->next->pre = head;
				delete temp;
				temp = nullptr;
				return;
			}
			//删除[1] - [length-1]时
			Node* previous = head;//指向当前要删除的元素的上一元素
			Node* now = head->next;//指向当前要删除的元素
			Node* next = now->next;//指向当前要删除的元素的下一元素
			for (int i = 0; i < num; i++) {
				previous = now;
				now = next;
				next = next->next;
				if (next == head) {
					cout << "输入的索引越界!!删除失败!!" << endl;
					return;
				}
			}
			previous->next = next;
			next->pre = previous;
			delete now;
			now = nullptr;
		}

		//修改数据(按索引修改)
		//参数:1.结点索引值(从0开始)  2.要更新的数据
		void UpdateNodeByIndex(int num, int value) {
			if (head->next == last) {
				cout << "为空表,不可修改数据!!" << endl;
				return;
			}
			//修改[0]时
			if (num == 0) {
				Node* temp = head->next;
				temp->data = value;
				return;
			}
			//修改[1] - [length-1]时
			Node* now = head->next;//指向当前要修改的元素
			for (int i = 0; i < num; i++) {
				now = now->next;
				if (now == last) {
					cout << "输入的索引越界!!修改失败!!" << endl;
					return;
				}
			}
			now->data = value;
		}
		
		//查询数据
		void DisplayList() {
			if (head->next == last) {
				cout << "该表为空!!" << endl;
				return;
			}
			Node* temp = head->next;
			while (temp != last) {
				cout << temp->data << " ";
				temp = temp->next;
			}
			cout << endl;
		}
};
int main() {
	DoubleLinkedList myDoubleList;

	for (int i = 0; i <= 10; i++) {
		myDoubleList.insertNode(i);
	}
	myDoubleList.DeleteNodeByIndex(5);
	myDoubleList.UpdateNodeByIndex(9, 50);
	myDoubleList.DisplayList();

	return 0;
}

运行效果:

你可能感兴趣的:(链表,c++,数据结构,算法)