素材巴巴 > 程序开发 >

模拟浏览器前进后退功能

程序开发 2023-09-03 17:28:34

首先需要两个栈,backStack用来后退的栈,forwardStack用来前进的栈。当我们发送back指令backStack就会从栈顶弹出我们需要访问的网址,当我们发送forward指令就会从forwardStack栈顶弹出一个网址。visit指令是访问当前的栈。

我们尝试命令行的方式实现。

代码如下:

package mainimport ("fmt"
 )/*
 模拟浏览器前进后退
 */
 func webBackForward() {// visit back forwardc := "" //commandcur := "http://www.baidu.com"fmt.Scanf("%s %s n", &c, &cur)c = "visit"printWeb(c, cur)back := make([]string, 0)forward := make([]string, 0)for c != "quit" && cur != "" {url := ""fmt.Scanf("%s %s n", &c, &url)if c == "visit" {back = append(back, cur)cur = urlprintWeb(c, cur)if len(forward) > 0 {forward = []string{}}} else if c == "back" {if len(back) > 0 {forward = append(forward, cur)cur = back[len(back)-1]back = back[:len(back)-1]printWeb(c, cur)} else {printWeb(c, "无法后退")}} else {if len(forward) > 0 {back = append(back, cur)cur = forward[len(forward)-1]forward = forward[:len(forward)-1]printWeb(c, cur)} else {printWeb(c, "无法前进")}}}}func printWeb(visit, cmd string) {fmt.Printf("当前访问 %s %s n", visit, cmd)
 }func main() {webBackForward()
 }
 

标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。