简介:栈是在现实工程项目中和算法比赛中最常用的数据结构之一,Java内置Stack数据结构,本文旨在用最简洁和快速的方式教会大家使用Stack。
从一个题目入手
/*这是一个模拟模拟栈的题目*/
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String [] args) throws Exception
{
Stack<Integer>stack = new Stack<Integer>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
while (n -- > 0)
{
String [] strs = reader.readLine().split(" ");
if (strs[0].equals("push"))
{
int x = Integer.parseInt(strs[1]);
// System.out.println("push");
stack.push(x);
}
else if (strs[0].equals("pop"))
{
// System.out.println("pop");
stack.pop();
}
else if (strs[0].equals("query"))
{
// System.out.println("query");
System.out.println(stack.peek());
}
else
{
// System.out.println("empty");
if (stack.empty()) System.out.println("YES");
else System.out.println("NO");
}
}
}
}
Stack<Integer>stack = new Stack<Integer>();
stack.push(x); // 往栈顶存放一个元素
stack.peek(); // 获取栈顶元素 但不把栈顶元素去掉
stack.pop(); // 把栈顶元素出栈 并且返回这个元素 这个是和c++的pop的区别 c++的不可以返回栈顶元素
stack.size(); // 获取栈的大小 这个和c++的一样 其他的STL容器获取大小也是这个
stack.isEmpty(); // 判断栈是否为空 返回boolean值 其他的容器也一般用这个方法
stack.search(); // 返回一个对象在此堆栈上的基于1的位置 意思是把栈顶的index作为1 让依次往下递增 以第一个出现的位置为准
import java.util.*;
public class Main{
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(5);
System.out.println("4:" + stack.search(4));
System.out.println("5:" + stack.search(5)); // 5处于栈顶位置
}
}
运行结果:
4:3
5:1
import java.util.*;
public class Main{
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
/*通过Iterator方式遍历*/
Iterator<Integer> it = stack.iterator();
while(it.hasNext())
{
System.out.print(it.next() + " ");
}
System.out.println();
/*通过for-each循环遍历*/
for(Integer it1:stack)
{
System.out.printf(it1 + " ");
}
System.out.println();
/*通过for遍历*/
for (int i = 0; i < stack.size(); ++ i)
{
System.out.print(stack.get(i) + " ");
}
/*
运行结果都是
1 2 3 4 5
*/
}
}
如果栈为空的话 使用pop()方法或者peek()方法会报错