一、Stack
示例:
package StackPack;
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<Integer> stack=new Stack<>();
for(int i=0;i<10;i++)
{
stack.push(i*2);
}
//[0, 2, 3, 4, 6, 8, 12, 14, 16, 18]
System.out.println(stack.peek()); //18
System.out.println(stack.search(14)); //以1为基数,
// 返回最近出现位置到栈顶距离,因此为3
while(!stack.isEmpty())
{
System.out.print(stack.pop()+"\t");
}
System.out.println();
System.out.println(stack.search(1)); //找不到,返回-1
}
}
二、Queue
由于Queue只是个接口,因此没有构造方法
从这里可以看到Queue从Collection中继承了add
,remove
等方法,但是我们应该尽量使用offer
替换add
,使用poll
来替换remove
使用Queue特有的方法offer
,poll
的好处是可以通过判断返回值判断操作是否成功完成,而add
,remove
则会在失败时抛出异常
示例:
package QueuePack;
import java.util.*;
public class QueueDemo {
public static void main(String[] args) {
Queue<Integer> queue=new ArrayDeque<>();
for(int i=0;i<10;i++)
{
queue.offer(i*2);
}
Iterator<Integer> it=queue.iterator();
while(it.hasNext())
{
System.out.print(it.next()+"\t"); //0 2 4 6 8 10 12 14 16 18
}
System.out.println();
System.out.println(queue.peek()); //0
System.out.println(queue.poll()); //0,同时队列变成[2,4,6,8,10,12,14,16,18]
}
}
示例:十进制转二进制
因为十进制转二进制是每次模2取余直到num=0,然后将余数反转即可得到转换的结果,因此可以利用双向队列Deque
代码
package QueuePack;
import java.util.*;
public class tenConvertTwo {
public static void main(String[] args) {
int num;
System.out.println("input Integer Num:");
Scanner scan=new Scanner(System.in);
num=scan.nextInt();
//双向队列
Deque queue=new LinkedList<>();
while(num!=0)
{
queue.push(num%2);
num/=2;
}
while(queue.size()!=0)
{
System.out.print(queue.pop());
}
}
}
Queue是单队列,Deque是双向队列,根据需要使用。
PS:此为学习笔记,如有错误,请友好指正,感谢。