1.使用LinkedList来实现
其实是利用其addLast方法
对于list, 依次加入1, 2, 3,list.add()实际是list.addLast();
class MyStack{
private LinkedList<Integer> list = new LinkedList<>();
public MyStack(){
}
public boolean isEmpty(){//判断是否为空
return list.isEmpty();
}
public int pop(){
if(!isEmpty()) return list.removeFirst();
else throw new EmptyStackException();
}
public void push(int val){
list.addFirst(val);
}
public void clear(){
list.clear();
}
}
本质是一个双向链表,用链表来实现
新建一个链表,Node类
新建一个stack
class Node{
Object data;
Node next;
public Node(Object val){
this.data = val;
this.next = null;
}
}
class MyStack{
Node head;//假的头结点
public MyStack(){
head = new Node(-1);
}
public boolean isEmpty(){
return head.next == null;
}
public void push(Object data){
Node node = new Node(data);
node.next = head.next;
head.next = node;
}
public Object pop(){
if(isEmpty()){
System.out.println("当前栈为空");
return -1;
}
Node next = head.next;
head.next = next.next;
return next.data;
}
public int size(){
if(isEmpty()) return 0;
Node now = head.next;
int cnt = 0;
while(now != null){
cnt++;
now = now.next;
}
return cnt;
}
}
3.使用数组来实现
class MyStack{
private int maxSize;
private int top;
private int[] arr;
public MyStack(int size){
maxSize = size;
top = -1;//这里top与数字下表直接对应
arr = new int[size];//初始化数组
}
public void push(int data){
arr[++top] = data;
}
public int pop(){
return arr[top--];//先取当前值,再自减
}
public int peek(){
return arr[top];
}
public boolean isEmpty(){
return top == -1;
}
public int size(){
return top;
}
}