资讯动态

利用栈处理 “..“ 回退目录。

发布时间:2026/8/10 12:50:06 来源:尧图企业网站定制
题目本质给一个 Linux 路径/a/./b/../../c/要求输出/ccpp #include iostream #include sstream #include stack #include string using namespace std; string simplifyPath(string path) { stackstring st; string cur; // 用 / 分割路径 stringstream ss(path); while (getline(ss, cur, /)) { // 空字符串或者 .直接忽略 if (cur.empty() || cur .) { continue; } // .. 表示返回上一级 if (cur ..) { if (!st.empty()) { st.pop(); } } // 普通目录压入栈 else { st.push(cur); } } // 栈中保存的是从根目录到当前目录的路径 string result; while (!st.empty()) { result / st.top() result; st.pop(); } // 如果最后没有目录说明就是根目录 if (result.empty()) { return /; } return result; } int main() { string path /a/./b/../../c/; string result simplifyPath(path); cout result endl; return 0; }

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价