基于动态数组的实现
/**
* 基于动态数组的栈
*
* @author ZhuZongxing
*/
public class ArrayStack<E> implements Stack<E> {
private Array<E> mArray;
public ArrayStack() {
this.mArray = new Array<>();
}
@Override
public int getSize() {
return mArray.getSize();
}
@Override
public boolean isEmpty() {
return mArray.isEmpty();
}
@Override
public void push(E e) {
mArray.addLast(e);
}
@Override
public E pop() {
return mArray.removeLast();
}
@Override
public E peek() {
return mArray.findLast();
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Stack: [");
for (int i = 0; i < mArray.getSize(); i++) {
stringBuilder.append(mArray.get(i));
if (i != mArray.getSize() - 1) {
stringBuilder.append(", ");
}
}
stringBuilder.append("] Top");
return stringBuilder.toString();
}
}
基于链表的栈的实现
/**
* 基于链表实现的栈
*
* @param <E> 泛型
* @author ZhuZongxing
*/
public class LinkedListStack<E> implements Stack<E> {
private LinkedList<E> list;
public LinkedListStack() {
this.list = new LinkedList<>();
}
@Override
public int getSize() {
return list.getSize();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public void push(E e) {
list.addFirst(e);
}
@Override
public E pop() {
return list.remove(0);
}
@Override
public E peek() {
return list.findFirst();
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("LinkedListStack: Top [");
for (int i = 0; i < list.getSize(); i++) {
stringBuilder.append(list.get(i));
if (i != list.getSize() - 1) {
stringBuilder.append(", ");
}
}
stringBuilder.append("]");
return stringBuilder.toString();
}
public static void main(String[] args) {
LinkedListStack<Integer> linkedListStack = new LinkedListStack<>();
for (int i = 0; i < 10; i++) {
linkedListStack.push(i);
}
System.out.println(linkedListStack);
linkedListStack.pop();
System.out.println(linkedListStack);
System.out.println(linkedListStack.peek());
}
}
网友评论