具体有难度的地方已在文中注释
栈的实现和大多数数据结构一样,底层依靠的是动态数组和链表,也就是数据结构里的顺序表和链表
1.顺序栈`
/**
* @author Jay
* @date 2020/7/10 8:55
* @Description:
*/
public class ArrayStack <E> {
Array<E> array;
public ArrayStack (){
array=new Array<>();
}
public ArrayStack(int capcity){
array=new Array<>(capcity);
}
public int getSize(){
return array.getSize();
}
public boolean isEmpty(){
return array.isEmpty();
}
public int getCapcity(){
return array.getCapacity();
}
public void push(E e){
array.addLast(e);
}
public E pop(){
return array.removeLast();
}
public E peek(){
return array.getLast();
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("Stack: ");
res.append('[');
for (int i = 0; i < array.getSize(); ++i) {
res.append(array.get(i));
if (i != array.getSize() - 1)
res.append(", ");
}
res.append("] top");
return res.toString();
}
}
2.链栈
/**
* @author Jay
* @date 2020/7/10 9:23
* @Description:
*/
public class LinkStack<E> {
LinkList<E> list;
public LinkStack(){
list=new LinkList<>();
}
public int getSize(){
return list.getSize();
}
public boolean isEmpty(){
return list.isEmpty();
}
public void push(E e){
list.addFirst(e);
}
public E pop(){
return list.removeFirst();
}
public E peek(){
return list.getFirst();
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("Stack: top ");
res.append(list);
return res.toString();
}
}