LinkedList(实现了queue,deque接口,List接口)实现栈和队列的功能
LinkedList是用双向链表结构存储数据的,很适合数据的动态插入和删除,随机访问和遍历速度比较慢。
底层是一个双向链表,链表擅长插入和删除操作,队列和栈最常用的2种操作都设计到插入和删除



import java.util.LinkedList; import java.util.Queue; //用linkedList模拟队列,因为链表擅长插入和删除 public class Hi { public static void main(String [] args) { //做剑指offer遇见过这个数结 Queue<String> queue = new LinkedList<String>(); //追加元素 queue.add("zero"); queue.offer("one"); queue.offer("two"); queue.offer("three"); queue.offer("four"); System.out.println(queue);//[zero, one, two, three, four] //从队首取出元素并删除 System.out.println(queue.poll());// zero System.out.println(queue.remove());//one System.out.println(queue);//[two, three, four] //从队首取出元素但是不删除 String peek = queue.peek(); System.out.println(peek); //two //遍历队列,这里要注意,每次取完元素后都会删除,整个 //队列会变短,所以只需要判断队列的大小即可 while(queue.size() > 0) { System.out.println(queue.poll()); }//two three four } }
//用linkedList模拟栈,因为链表擅长插入和删除
import java.util.Deque;
import java.util.LinkedList;
public class Hi {
public static void main(String[] args) {
/*模拟栈,这是从头开始进来的*/
Deque<String> deque = new LinkedList<String>();
/*Pushes an element onto the stack
*at the head of this dequeue */
deque.push("a");
deque.push("b");
deque.push("c");
System.out.println(deque); //[c, b, a]
//获取栈首元素后,元素不会出栈
System.out.println(deque.peek());//c
while(deque.size() > 0) {
//获取栈首元素后,元素将会出栈
System.out.println(deque.pop());//c b a
}
System.out.println(deque);//[]
/*模拟栈*/
deque.offerLast("a");
deque.offerLast("b");
deque.offerLast("c");// [a, b, c]
while(!deque.isEmpty())
System.out.println(deque.pollLast());
} // 先输出c再b最后a
}
import java.util.Stack;
//没有用到接口编程
public class Hi {
public static void main(String[] args) {
Stack<Integer> s = new Stack<Integer>();
s.push(1);
s.push(2);// [1,2]
s.push(3);// [1,2,3]
while(!s.isEmpty()){
System.out.println(s.pop());
}//依次输入 3 接着是2 ,然后1
}
}
浙公网安备 33010602011771号