数据结构--栈

特点 :先进后出

栈就像是堆箱子,第一个放入的箱子需要最后才能取到

实现:

链表实现

链表节点的实现
--------------------------------------------------------------------------------

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值