栈,只有一端可以操作,也就是栈头
先进后出,后进先出
链表实现
package com.zwz.stack;
import java.util.Iterator;
public class StackServiceImpl<E> implements StackService<E>{
static class Stack<E>{
E value;
Stack<E> next;
public Stack(E value, Stack next) {
this.value = value;
this.next = next;
}
}
int capacity = 10;
int size = 0;
Stack<E> head = new Stack<>(null,null);
@Override
public Boolean push(E value) {
if(isFull()){
return null;
}
head.next = new Stack<>(value,head.next);
size++;
return null;
}
@Override
public E pull() {
if (isEmpyt()){
return null;
}
Stack<E> next = head.next;
head.next = next.next;
size--;
return next.value;
}
@Override
public E peek() {
if (isEmpyt()){
return null;
}
return head.next.value;
}
@Override
public Boolean isFull() {
return capacity == size;
}
@Override
public Boolean isEmpyt() {
return head.next == null;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
Stack<E> stack = head;
@Override
public boolean hasNext() {
return stack.next != null;
}
@Override
public E next() {
E value = stack.next.value;
stack = stack.next;
return value;
}
};
}
}
数组实现
package com.zwz.stack;
import java.util.Iterator;
public class StackServiceImpl2<E> implements StackService<E> {
@SuppressWarnings("all")
E[] node = (E[]) new Object[20];
int index = 0;
@Override
public Boolean push(E value) {
if (isFull()) {
return false;
}
node[index] = value;
index++;
return true;
}
@Override
public E pull() {
if (isEmpyt()) {
return null;
}
E e = node[index-1];
index--;
return e;
}
@Override
public E peek() {
if (isEmpyt()) {
return null;
}
return node[index-1];
}
@Override
public Boolean isFull() {
return index == node.length;
}
@Override
public Boolean isEmpyt() {
return index == 0;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
E[] values = node;
int size = values.length-1;
@Override
public boolean hasNext() {
return size >= 0;
}
@Override
public E next() {
E value = values[size];
size--;
return value;
}
};
}
}