目录
1.如何实现栈
可以采用数组与链表这两种方法来实现栈。
给出链表的方法实现栈:
class Node<E> {
Node<E> next=null;
E data;
public Node(){}
public Node(E data){
this.data=data;
}
}
public class Stack<E> {
Node<E> top = null;
public boolean isEmpty(){
return top == null;
}
public void push(E data){
Node<E> p = new Node<E>(data);
p.next=top;
top=p;
}
public E pop(){
if(this.isEmpty())
return null;
E data = top.data;
top=top.next;
return data;
}
public E peek(){
if(this.isEmpty())
return null;
return top.data;
}
}
2.如何用O(1)时间复杂度求栈中最小元素
public class MyStack {
Stack<Integer> elem;
Stack<Integer> min;
public MyStack(){
elem=new Stack<Integer>();
min=new Stack<Integer>();
}
public void push(int data){
elem.push(data);
if(min.isEmpty())
min.push(data);
else{
if(data<min.peek())
min.push(data);
}
}
public int pop(){
int topData=elem.peek();
elem.pop();
if(topData==this.min())
min.pop();
return topData;
}
public int min(){
if(min.isEmpty())
return Integer.MAX_VALUE;
else
return min.peek();
}
}
3.如何实现队列
给出链表方式实现队列:
public class MyQueue<E> {
private Node<E> head = null;
private Node<E> tail = null;
public boolean isEmpty(){
return head==null;
}
public void put(E data){
Node<E> p = new Node<E>(data);
if(head==null && tail==null) //队列为空
head=tail=p;
else{
tail.next=p;
tail=p;
}
tail.next=null;
}
public E pop(){
if(this.isEmpty())
return null;
E data = head.data;
head=head.next;
return data;
}
public int size(){
Node<E> tmp = head;
int n=0;
while(tmp!=null){
n++;
tmp=tmp.next;
}
return n;
}
public static void main(String[] args) {
MyQueue<Integer> q= new MyQueue<>();
q.put(111);
q.put(222);
q.put(666);
q.put(777);
System.out.println("队列长度: "+q.size());
System.out.println("队首元素: "+q.pop());
System.out.println("队首元素: "+q.pop());
System.out.println("队列长度: "+q.size());
System.out.println("队首元素: "+q.pop());
System.out.println("队首元素: "+q.pop());
}
}
结果:
还有一种数组实现队列的方式,为了实现多线程安全,增加了对队列操作的同步。
import java.util.LinkedList;
public class MyQueue<E>{
private LinkedList<E> list = new LinkedList<E>();
private int size=0;
public synchronized void put(E e){
list.addLast(e);
size++;
}
public synchronized E pop(){
size--;
return list.removeFirst();
}
public synchronized boolean empty(){
return size==0;
}
public synchronized int size(){
return size;
}
}
4.如何实现用两个栈模拟队列操作
A为插入栈,B为弹出栈。要入队列,入栈A即可,出队列需要分两种情况考虑:
1)若栈B不为空,直接弹出栈B的数据。
2)若栈B为空,依次弹出栈A数据压入栈B中,再依次弹出栈B数据。
以下采用Java内置的Stack实现:
import java.util.Stack;
public class MyQueue<E>{
private Stack<E> s1 =new Stack<E>();
private Stack<E> s2 =new Stack<E>();
public synchronized void put(E e){
s1.push(e);
}
public synchronized E pop(){
if(s2.isEmpty())
while(!s1.isEmpty())
s2.push(s1.pop());
return s2.pop();
}
public synchronized boolean empty(){
return s1.isEmpty()&&s2.isEmpty();
}
public static void main(String[] args) {
MyQueue<Integer> q = new MyQueue<>();
q.put(1);
q.put(2);
System.out.println("队列首元素: "+q.pop());
System.out.println("队列首元素: "+q.pop());
}
}
结果: