下压栈、队列、栈在java的基本实现
1.下压栈
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
public class ResizingArrayStack<T> implements Iterable<T> {
private T[] a= (T[]) new Object[1];
private int N=0;
public boolean isEmpty(){
return N==0;
}
public int size(){
return N;
}
private void resize(int max){
T[] t= (T[]) new Object[max];
for (int i=0;i<N;i++){
t[i]=a[i];
}
a=t;
}
public void push(T t){
if (a.length==N) resize(2*N);
a[N++]=t;
}
public T pop(){
T t =a[--N];
a[N]=null;
if (N>0&&N==a.length/4){
resize(a.length/2);
}
return t;
}
@Override
public Iterator<T> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<T>{
int i =N;
@Override
public boolean hasNext() {
return i>0;
}
@Override
public T next() {
return a[--i];
}
@Override
public void remove() {
}
@Override
public void forEachRemaining(Consumer<? super T> action) {
}
}
@Override
public void forEach(Consumer<? super T> action) {
}
@Override
public Spliterator<T> spliterator() {
return null;
}
}
2. 先进先出的队列
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Stack;
import java.util.function.Consumer;
public class Queue<T> implements Iterable<T> {
private Node first;
private Node last;
private int N;
private class Node{
T t;
Node next;
}
public boolean isEmpty(){
return first==null;
}
public int size(){
return N;
}
public void enqueue(T ele){
Node oldLast=last;
last=new Node();
last.t=ele;
last.next=null;
if(isEmpty()){
first=last;
}else {
oldLast.next=last;
}
N++;
}
public T dequeue(){
T ele=first.t;
first=first.next;
if (isEmpty()){
last=null;
}
N--;
return ele;
}
@Override
public Iterator<T> iterator() {
return null;
}
@Override
public void forEach(Consumer<? super T> action) {
}
@Override
public Spliterator<T> spliterator() {
return null;
}
}
3. 链栈
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
public class Stack<T> implements Iterable<T>{
private Node first;
private int N;
private class Node{
T t;
Node next;
}
public boolean isEmpty(){
return first==null;
}
public int size(){
return N;
}
public void push(T e){
Node oldFirst=first;
first=new Node();
first.t=e;
first.next=oldFirst;
N++;
}
public T pop(){
T ele=first.t;
first=first.next;
N--;
return ele;
}
@Override
public Iterator<T> iterator() {
return null;
}
@Override
public void forEach(Consumer<? super T> action) {
}
@Override
public Spliterator<T> spliterator() {
return null;
}
}