1.LinkedList快速实现栈
概要:Java 有Stack类(已经过时),无专门的Stack接口,栈相关方法包括在双端队列接口Deque中。LinkedList实现了Deque接口。
3个常用方法:
- E peek () 返回栈顶元素,没有则返回null。
- void push(E e) 压栈
- E pop () 出栈
简单例子:
package com.company;
import java.util.Deque;
import java.util.LinkedList;
public class MyStack<E> {
Deque <E> myStack;
public MyStack(){
myStack=new LinkedList<>();
}
public void push(E val){
myStack.push(val);
}
public void pop(){
myStack.pop();
}
public E get(){
return myStack.peek();
}
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
MyStack<Integer> myStack=new MyStack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
System.out.println(myStack.get());
myStack.pop();
System.out.println(myStack.get());
myStack.pop();
System.out.println(myStack.get());
myStack.pop();
System.out.println(myStack.get());
myStack.pop();
System.out.println(myStack.get());
}
}
输出结果:
4
3
2
1
null
2.LinkedList快速实现队列
概要:deque接口继承queue接口,LinkedList实现deque接口。
3对常用方法 (Queue.java 中Queue接口的所有方法):
boolean add(E e); //
boolean offer(E e);
E remove();
E poll();
E element();
E peek();
add()和offer()尾部添加数据
区别:add()会在长度不够时抛出异常:IllegalStateException; offer()则不会,只返回false,本次笔记用LinkedList实现Queue,由于LinkedList基于双向列表实现,故不会出现该异常。
remove()和poll()头部删除数据
区别:remove()会在没元素时抛出异常:NoSuchElementException; poll()返回null;
element()和peek()查看头部数据
区别:element()会在没元素时抛出异常:NoSuchElementException; peek()返回null;
注意:leetcode题解常用offer()和poll();
package com.company;
import java.util.LinkedList;
import java.util.Queue;
public class MyQueue <E> {
Queue <E> myQueue;
public MyQueue(){
myQueue=new LinkedList<>();
}
public boolean add(E e){
return myQueue.add(e);
}
public boolean offer(E e){
return myQueue.offer(e);
}
public E remove(){
return myQueue.remove();
}
public E poll(){
return myQueue.poll();
}
public E element(){
return myQueue.element();
}
public E peek(){
return myQueue.peek();
}
}
MyQueue<Double> myQueue = new MyQueue<>();
myQueue.add(5.0);
myQueue.add(6.0);
myQueue.offer(7.0);
myQueue.offer(8.0);
System.out.println(myQueue.peek());
myQueue.remove();
System.out.println(myQueue.peek());
myQueue.remove();
System.out.println(myQueue.peek());
myQueue.poll();
System.out.println(myQueue.element());
myQueue.poll();
try{
myQueue.remove();
}catch(NoSuchElementException e){
System.out.println("11111");
}
try{
System.out.println(myQueue.element());
System.out.println(myQueue.element());
}catch (NoSuchElementException e){
System.out.println("22222");
}
运行结果:
5.0
6.0
7.0
8.0
11111
22222