栈
特点 :先进后出
栈就像是堆箱子,第一个放入的箱子需要最后才能取到
实现:
链表实现
链表节点的实现
--------------------------------------------------------------------------------
public class ListNode {
//当前节点的值
int value;
//下一个节点的地址域
ListNode next;
public ListNode(int value) {
this.value = value;
}
}
实现栈
--------------------------------------------------------------------------------
ListNode head;
//站内元素数目
public int h=0;
//栈的大小
public int size=0;
public Stack(int size){
head=null;
h=0;
this.size=size;
}
判栈满
--------------------------------------------------------------------------------
// 判断栈满
public boolean isFull(){
if (size==h){
return true;
}else{
return false;
}
}
判栈空
--------------------------------------------------------------------------------
// 判断栈空
public boolean isEmpty(){
if (h==0){
return true;
}else {
return false;
}
}
入栈
--------------------------------------------------------------------------------
// 入栈
public void push(int x){
if (isFull()){
System.out.println("栈满了");
}else{
ListNode t=new ListNode(x);
t.next=head;
head=t;
h++;}
}
出栈
--------------------------------------------------------------------------------
public int pop(){
if (isEmpty()){
System.out.println("栈空");
return 0;
}else{
int value= head.value;
head.next=head;
return value;
}
}
数组实现
实现栈
--------------------------------------------------------------------------------
private int[] arr;
private int flag =0;
public Stack(int size){
arr = new int[size];
}
入栈
--------------------------------------------------------------------------------
public void push(int x){
if (flag ==arr.length){
int[] temp=new int[arr.length*2];
for (int i=0;i<arr.length;i++){
temp[i] = arr[i];
}
arr =temp;
}
arr[flag]=x;
flag+=1;
}
出栈
--------------------------------------------------------------------------------
public int pop(){
int value=arr[flag];
flag--;
return value;
}