有没有oop高手,双向循环链表做不了吗
查看原帖
有没有oop高手,双向循环链表做不了吗
555584
weiming3楼主2023/3/3 08:00

写起来特别简单,但最后有几个点TLE,我怀疑是链表本身的低效导致的,有没有什么优化方法

#include <iostream>
using namespace std;
template <typename T>
class Node {
	public:
		T occupation;
		int  face;
		Node* prev;
		Node* next;
		Node(T data, int face) {
			this->occupation = data;
			this->face = face;
			prev = nullptr;
			next = nullptr;
		}
};
template<typename T>
class DoubleCircleLinkedList {
	private:
		Node<T> * head;
		Node<T>* tail;
		Node<T>* inv;
	public:
		DoubleCircleLinkedList() {
			head = nullptr;
			tail = nullptr;
			inv=nullptr;
			
			
		}
		bool is_empty() {
			if (head == nullptr && tail == nullptr) {
				return true;
			} else {
				return false;
			}
		}
		void append(T data, int face) {
			Node<T>* newNode = new Node<T>(data, face);
			if (!is_empty()) {
				newNode->prev = tail;
				newNode->next = head;
				tail->next = newNode;
				head->prev = newNode;
				tail = newNode;
				inv=head;
				
			} else {
				newNode->next = newNode;
				newNode->prev = newNode;
				inv=head;
				head = newNode;
				tail = newNode;
			}
		}
		T command(int a, int s) {
			Node<T>* t = inv;
			if (t->face == 0) {
				if (a == 0) {
					for (int i = 1; i <= s; i++) {
						t = t->prev;
					}
				} else {
					for (int i = 1; i <= s; i++) {
						t = t->next;
					}
				}
			} else {
				if (a == 0) {
					for (int i = 1; i <= s; i++) {
						t = t->next;
					}
				} else {
					for (int i = 1; i <= s; i++) {
						t = t->prev;
					}
				}
			}
			inv=t;
			return t->occupation;
		}
};
int main() {
	int n, m;
	cin >> n >> m;
	DoubleCircleLinkedList<string> d;
	for (int i = 1; i <= n; i++) {
		int t1;
		string t2;
		cin >> t1 >> t2;
		d.append(t2, t1);
	}
	string k;
	
	for (int i = 1; i <= m; i++) {
		int p, q;
		cin >> p >> q;
		k = d.command(p, q);
	}
	cout << k;
	return 0;
}
2023/3/3 08:00
加载中...