数据结构:Stack
// Stack.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <stdio.h> #include <string> using namespace std; //这里用的是链表节点实现的Node struct DataNode { int data; DataNode* prev; DataNode() { prev = nullptr; } }; class Stack { public: Stack() :size(0) {} void Push(int val) { if (root == nullptr) { root = new DataNode(); root->data = val; cur = root; minVal = val; } else { DataNode* node = new DataNode(); node->prev = cur; node->data = val; cur = node; size++; if (minVal > val) { minVal = val; } } } void Pop() { if (cur->prev != nullptr) { DataNode* d = cur->prev; delete cur; cur = d; size--; } } int Top() { return cur->data; } int Size() { return size; } int Min() { int min_val = cur->data; DataNode* node = cur; while (node != nullptr) { if (min_val > node->data) { min_val = node->data; } node = node->prev; } return min_val; } private: int minVal; DataNode* root; //当前栈底节点 DataNode* cur; //当前top节点 int size; }; int main() { Stack s; s.Push(5); s.Push(6); s.Push(7); s.Push(3); s.Push(1); printf("top:%d,min:%d,size:%d", s.Top(), s.Min(), s.Size()); // 5 6 7 3 1 string line; cout << "0 pop 1 print 2 min" << endl; while (line != "exit") { cin >> line; //getline(cin, line); if (line == "0") { s.Pop(); printf("top:%d,min:%d,size:%d",s.Top(), s.Min(), s.Size()); } if (line == "1") { cout << "top" << s.Top() << endl; printf("top:%d,min:%d,size:%d",s.Top(), s.Min(), s.Size()); } if (line == "2") { cout << "Min" << s.Min() << endl; } } return 0; }