自定义栈实现:
public class MibuStack<T> {
// 定义小大
private int size;
// 默认数据大小为4
private Object[] array = new Object[4];
// 非空判断函数
public boolean isEmpty(){
if (size==0) {
return true;
}else{
return false;
}
}
public int size(){
return size;
}
// 扩容函数
public void expandCapacity(){
Object[] newArray = new Object[size*2];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
// 向栈内压元素
public void push(T t){
array[size]=t;
size++;
if(size==array.length){
expandCapacity();
}
}
// 弹出栈顶元素
@SuppressWarnings("unchecked")
public T peek(){
if (isEmpty()) {
return null;
}else{
return (T) array[size-1];
}
}
// 移除栈顶元素
public T pop(){
if (isEmpty()) {
return null;
} else {
T t = peek();
array[size-1]=null;
size--;
return t;
}
}
}
自定义队列实现:
public class MyQueue<T> {
private int size;
public boolean isEmpty(){
if (size==0) {
return true;
}else{
return false;
}
}
public int size(){
return size;
}
private ListNode<T> head;
private ListNode<T> last;
public MyQueue(ListNode<T> head, ListNode<T> last) {
super();
head = new ListNode<T>(null, null) ;
last = head;
}
public void offer(T t){
ListNode<T> node = new ListNode<T>(t, null);
last.next=node;
last=node;
size++;
}
public T peek(){
if (isEmpty()) {
return null;
} else {
return head.next.value;
}
}
public T poll(){
if (isEmpty()) {
return null;
} else {
ListNode<T> p=head.next;
head.next=p.next;
size--;
if (size==0) {
last=head;
}
return p.value;
}
}
}
class ListNode<T>{
T value;
ListNode<T> next;
public ListNode(T value, ListNode<T> next) {
super();
this.value = value;
this.next = next;
}
}