Java数据结构之栈的实例应用攻略
1. 栈的概述
栈是一种具有特定操作规则的线性数据结构,遵循先进后出(Last-In-First-Out,LIFO)的原则。栈的操作包括入栈(push)和出栈(pop),以及获取栈顶元素(peek)等。
2. 栈的实例应用
2.1. 括号匹配
栈在括号匹配问题中有广泛的应用。通过使用栈,我们可以检查一个字符串中的括号是否匹配。
示例代码:
import java.util.Stack;
public class BracketMatching {
public static boolean isBracketMatching(String input) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else if (ch == ')' || ch == ']' || ch == '}') {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((ch == ')' && top != '(') || (ch == ']' && top != '[') || (ch == '}' && top != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String input1 = \"((()))\";
String input2 = \"({[]})\";
String input3 = \"({[)})\";
System.out.println(isBracketMatching(input1)); // Output: true
System.out.println(isBracketMatching(input2)); // Output: true
System.out.println(isBracketMatching(input3)); // Output: false
}
}
2.2. 浏览器的前进后退功能
栈在浏览器的前进后退功能中也有应用。当用户点击浏览器的前进或后退按钮时,浏览器会将当前页面的URL入栈或出栈,以便在需要时可以回退到上一个页面或前进到下一个页面。
示例代码:
import java.util.Stack;
public class BrowserHistory {
private Stack<String> backStack;
private Stack<String> forwardStack;
private String currentURL;
public BrowserHistory() {
backStack = new Stack<>();
forwardStack = new Stack<>();
currentURL = \"\";
}
public void visit(String url) {
backStack.push(currentURL);
currentURL = url;
forwardStack.clear();
}
public boolean canGoBack() {
return !backStack.isEmpty();
}
public boolean canGoForward() {
return !forwardStack.isEmpty();
}
public String goBack() {
if (canGoBack()) {
forwardStack.push(currentURL);
currentURL = backStack.pop();
return currentURL;
}
return \"\";
}
public String goForward() {
if (canGoForward()) {
backStack.push(currentURL);
currentURL = forwardStack.pop();
return currentURL;
}
return \"\";
}
public String getCurrentURL() {
return currentURL;
}
public static void main(String[] args) {
BrowserHistory history = new BrowserHistory();
history.visit(\"https://www.google.com\");
history.visit(\"https://www.openai.com\");
history.visit(\"https://www.github.com\");
System.out.println(history.getCurrentURL()); // Output: https://www.github.com
System.out.println(history.canGoBack()); // Output: true
System.out.println(history.goBack()); // Output: https://www.openai.com
System.out.println(history.canGoForward()); // Output: true
System.out.println(history.goForward()); // Output: https://www.github.com
System.out.println(history.getCurrentURL()); // Output: https://www.github.com
}
}
以上是关于Java数据结构中栈的实例应用的攻略,希望对你有所帮助!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java数据结构关于栈的实例应用 - Python技术站