#include <iostream> #include <stdio.h> #include <string> using namespace std; struct DequeNode { int Data; //无论是插入或者删除都需要更新prev next DequeNode* prev; DequeNode* next; DequeNode() { prev = nullptr; next = nullptr; Data = 0; } DequeNode* CreateNextNode(int val) { DequeNode* node = new DequeNode(); node->prev = this; this->next = node; node->Data = val; return node; } DequeNode* CreatePrevNode(int val) { DequeNode* node = new DequeNode(); node->next = this; this->prev = node; node->Data = val; return node; } }; //再出站的时候会导致Min不准确 class Deque { public: Deque() { head = nullptr; tail = nullptr; size = minVal = 0; } void push_back(int val) { if (tail == nullptr) { tail = new DequeNode(); tail->Data = val; head = tail; minVal = val; size++; } else { tail = tail->CreateNextNode(val); /*tail->next = new DequeNode(); tail->next->Data = val; tail->next->prev = tail; tail = tail->next;*/ if (minVal > val) minVal = val; size++; } } void push_front(int val) { if (head == nullptr) { head = new DequeNode(); head->Data = val; minVal = val; tail = head; size++; } else { head = head->CreatePrevNode(val); //head->prev = new DequeNode(); //head->prev->Data = val; if (minVal > val) minVal = val; //head->prev->next = head; //head = head->prev; size++; } } int front() { if (head == nullptr) { return -1; } return head->Data; } int back() { if (tail == nullptr) { return -1; } return tail->Data; } void pop_front() { if (size == 0) { head = tail = nullptr; return; } if (head->next != nullptr) { DequeNode* node = head->next; delete head; head = node; head->prev = nullptr; size--; } } void pop_back() { if (size == 0) { head = tail = nullptr; return; } if (tail->prev != nullptr) { DequeNode* node = tail->prev; delete tail; tail = node; tail->next = nullptr; size--; } } //从头节点直接遍历到结尾节点 int min_val() { int min_val = head->Data; DequeNode* node = head; while (node != nullptr) { if (min_val > node->Data) { min_val = node->Data; } node = node->next; } return min_val; } int Size() { return size; } private: //这个是root节点 DequeNode* head;//用于后向插入 DequeNode* tail; //用于前向插入 int size; int minVal; }; int maind() { Deque s; /*s.push_back(5); s.push_back(6); s.push_back(7); s.push_back(3); s.push_back(1);*/ s.push_front(1); s.push_front(3); s.push_front(7); s.push_front(6); s.push_front(5); printf("deque:front:%d,back:%d,min:%d", s.front(), s.back(), s.min_val()); printf("size:%d ", s.Size()); // 5 6 7 3 1 std::string line; cout << "0 popfront 1 popback 2 front 3 back 4 min" << endl; while (line != "exit") { cin >> line; //getline(cin, line); if (line == "0") { s.pop_front(); printf("deque:front:%d,back:%d,min:%d", s.front(), s.back(), s.min_val()); } if (line == "1") { s.pop_back(); printf("deque:front:%d,back:%d,min:%d", s.front(), s.back(), s.min_val()); } } return 0; }