栈的实现,通过链表实现
public class Stack {
private class Node{
int val;
Node next;
public Node(int val){
this.val=val;
}
}
private Node head=null;
private int size=0;
public void push(int val){
Node newNode=new Node(val);
if(head==null){
head=newNode;
return;
}
newNode.next=head;
head=newNode;
size++;
}
public Integer pop(){
if (head==null){
return null;
}
if (head.next==null){
int res=head.val;
head=null;
size--;
return res;
}
int temp=head.val;
head=head.next;
size--;
return temp;
}
public Integer peek(){
if (head==null){
return null;
}
return head.val;
}
public int size(){
return size;
}
public void clear(){
head=null;
}
public boolean isEmpty(){
return size==0;
}
}