链接:http://bailian.openjudge.cn/practice/1028/
1028:Web Navigation
-
描述
-
Standard web browsers contain features to move backward and forward among the pages recently visited. One way to implement these features is to use two stacks to keep track of the pages that can be reached by moving backward and forward. In this problem, you are asked to implement this.
The following commands need to be supported:
BACK: Push the current page on the top of the forward stack. Pop the page from the top of the backward stack, making it the new current page. If the backward stack is empty, the command is ignored.
FORWARD: Push the current page on the top of the backward stack. Pop the page from the top of the forward stack, making it the new current page. If the forward stack is empty, the command is ignored.
VISIT : Push the current page on the top of the backward stack, and make the URL specified the new current page. The forward stack is emptied.
QUIT: Quit the browser.
Assume that the browser initially loads the web page at the URL http://www.acm.org/
输入
- Input is a sequence of commands. The command keywords BACK, FORWARD, VISIT, and QUIT are all in uppercase. URLs have no whitespace and have at most 70 characters. You may assume that no problem instance requires more than 100 elements in each stack at any time. The end of input is indicated by the QUIT command. 输出
- For each command other than QUIT, print the URL of the current page after the command is executed if the command is not ignored. Otherwise, print "Ignored". The output for each command should be printed on its own line. No output is produced for the QUIT command.
解题思路
这是一个栈的操作的题目,前进后退等相当于栈的栈的操作。深入理解栈的操作此题易解。
代码如下:
import java.util.Scanner;
public class Main {
private String[] fstack=new String [100];
private String[] bstack=new String [100];
private String current="http://www.acm.org/";
private int ftop=-1;
private int btop=-1;
public Main(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
Main m=new Main();
while(true){
String commond="";String str="";
commond=scan.next();
if(commond.equals("QUIT")) break;
if(commond.equals("VISIT")){
str=scan.next();
}
m.operate(commond, str);
}
scan.close();
}
private String back(){
if(btop==-1){
return "Ignored";
}
ftop++;
fstack[ftop]=current;
current=bstack[btop];
btop--;
return current;
}
private String forward(){
if(ftop==-1){
return "Ignored";
}
btop++;
bstack[btop]=current;
current=fstack[ftop];
ftop--;
return current;
}
private void visit(String string){
btop++;
bstack[btop]=current;
ftop=-1;
current=string;
}
public String operate(String commond,String str){
//System.out.println(commond+str);
switch(commond){
case "BACK": System.out.println(back());break;
case "FORWARD":System.out.println(forward());break;
case "VISIT":visit(str);System.out.println(str);break;
default:System.out.println("WRONG");
}
return null;
}
}