源代码

// 初始化栈和当前页面
const backStack = []; // 后退栈
const forwardStack = []; // 前进栈
let currentPage = "http://www.acm.org/"; // 初始页面

// 模拟输入(实际应用中可以从控制台读取)
const input = [
    "VISIT http://acm.ashland.edu/",
    "VISIT http://acm.baylor.edu/acmicpc/",
    "BACK",
    "BACK",
    "BACK",
    "FORWARD",
    "VISIT http://www.ibm.com/",
    "BACK",
    "BACK",
    "FORWARD",
    "FORWARD",
    "QUIT"
];

// 循环处理输入
for (const line of input) {
    const parts = line.split(" ");
    const command = parts[0];

    if (command === "QUIT") {
        break; // 退出循环
    } else if (command === "BACK") {
        if (backStack.length > 0) {
            forwardStack.push(currentPage); // 当前页面进入前进栈
            currentPage = backStack.pop(); // 从后退栈中取出新的当前页面
            console.log(currentPage);
        } else {
            console.log("Ignored");
        }
    } else if (command === "FORWARD") {
        if (forwardStack.length > 0) {
            backStack.push(currentPage); // 当前页面进入后退栈
            currentPage = forwardStack.pop(); // 从前进栈中取出新的当前页面
            console.log(currentPage);
        } else {
            console.log("Ignored");
        }
    } else if (command === "VISIT") {
        const url = parts[1];
        backStack.push(currentPage); // 当前页面进入后退栈
        currentPage = url; // 更新当前页面
        forwardStack.length = 0; // 清空前进栈
        console.log(currentPage);
    }
}

运行结果

http://acm.ashland.edu/ http://acm.baylor.edu/acmicpc/ http://acm.ashland.edu/ http://www.acm.org/ Ignored http://acm.ashland.edu/ http://www.ibm.com/ http://acm.ashland.edu/ http://www.acm.org/ http://acm.ashland.edu/ http://www.ibm.com/