2014-03-18 03:19
题目:用一个数组实现3个栈。
解法:
首先我想过让三个栈动态决定长度。要么左右各一个向中间靠拢,要么三个穿插着,后来都觉得实现起来太复杂,而且思路总有各种功能缺陷,会导致额外的时间或空间复杂度。所以,还是三等分成固定大小吧。好写又好用。
代码:
// 3.1 Use an array to implement three stacks. // three fixed-length stacks #include <cstdio> #include <cstring> #include <vector> using namespace std; template <class T> class ThreeStack { public: ThreeStack(size_t _total_capacity = 1): total_capacity(_total_capacity) { msize[0] = 0; msize[1] = 0; msize[2] = 0; mcapacity[0] = mcapacity[1] = mcapacity[2] = total_capacity / 3; mcapacity[0] += (total_capacity % 3 != 0 ? 1 : 0); mcapacity[1] += (total_capacity % 3 == 2 ? 1 : 0); offset[0] = 0; offset[1] = offset[0] + mcapacity[0]; offset[2] = offset[1] + mcapacity[1]; mdata.resize(total_capacity); } ~ThreeStack() { mdata.clear(); } void push(int idx, T val) { if (msize[idx] == mcapacity[idx]) { // this stack is full return; } mdata[offset[idx] + msize[idx]] = val; ++msize[idx]; } void pop(int idx) { if (msize[idx] == 0) { return; } --msize[idx]; } T top(int idx) { if (msize[idx] == 0) { return mdata[-1]; } return mdata[offset[idx] + msize[idx] - 1]; } size_t size(int idx) { return msize[idx]; } private: // total capacity of all stack size_t total_capacity; // starting offset for each stack size_t offset[3]; // capacities of the three stacks size_t mcapacity[3]; // sizes of the three stacks size_t msize[3]; // the data in the stacks vector<T> mdata; }; int main() { int n; size_t idx; int val; char str[100]; scanf("%d", &n); ThreeStack<int> ts(n); while (scanf("%s", str) == 1) { if (strcmp(str, "end") == 0) { break; } else if (strcmp(str, "push") == 0) { scanf("%u%d", &idx, &val); ts.push(idx, val); } else if (strcmp(str, "pop") == 0) { scanf("%u", &idx); ts.pop(idx); } else if (strcmp(str, "top") == 0) { scanf("%u", &idx); printf("top[%u] = %d\n", idx, ts.top(idx)); } else if (strcmp(str, "size") == 0) { scanf("%u", &idx); printf("size[%u] = %u\n", idx, ts.size(idx)); } } return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)