栈和队列

栈和队列

一、栈
方法调用栈:JVM内存区域中一块特殊区域,用来存放方法之间的调用关系
1. 定义:
栈是一种特殊的线性表,只允许在一端进行插入和删除。进行插入和删除的一端称为栈顶,另一端是栈底。栈中元素遵守先进后出的原则。
关于栈的核心操作:
入栈/压栈/进栈:将元素放进栈里
出栈:把最后入栈的元素取出来删除
取栈顶操作:获取最后一个入栈元素的结果
2.栈的实现
<1>.利用顺序表实现,即利用尾插入栈,尾删出栈,根据下标获取元素的操作表示取栈顶元素。

public class MyStack{
     //首先构建一个顺序表
        private int[] array=new int[100];  
        private int size=0;
         //入栈
  public void push(int val){
          //入栈尾插,则要考虑栈满
           if(size>array.size){
              return;
              }
           array[size]=val;
           size++;
       }
       //出栈
  public int pop(){
  //出栈尾删,则要考虑顺序表是否为空
          if(size==0){
              return null;
              }
          int ret=array[size-1];
          size--;
          return ret;
     }
     //取栈顶元素
     public int peek(){
     //首先考虑顺序表是否为空
            if(size==0){
                return null;
            }
         return array[size-1];
   }

<2>.利用链表实现,头插表示入栈,头删表示出栈,直接取头节点表示取栈顶元素。

public class MyStack{
      private Node head=null;
      //入栈
      public void push(int val){
      //头插入栈,首先考虑链表为空的情况
           if(head==null){
           head=newNode;
           return;
           }
           newNode.next=head;
           head=newNode;
     }
     //出栈
     public int pop(){
         //出栈头删,首先考虑栈空
          if(head==null){
             return null;
             }
         //再考虑只有一个元素
         if(head.next==null){
           int ret=head.val;
           head=null;
           return ret;
           }
           int ret=head.val;
           head=head.next;
           return ret;
     }
//取栈顶元素
   public int peek(){
        if(head==null){
            return null;
            }
       return head.val;
       }
     

二、队列
1. 定义:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表。 队列元素遵守 “先进先出” 的原则。
2.队列的实现
队列使用链表更好一些,顺序表和数组的效率会比较低。
入队列:尾部插入
出队列:头部删除
取队首元素:直接获取头节点

class Node{
    int val;
    Node next;
    }
    Node(int val,Node next){
        this.val=val;
        this.next=next;
        }
public class MyQueue{
   private  Node head=null;
   private  Node tail=null;
   private int size=0;
   //入队列(尾部插入)
  public boolean offer(int val){
     //考虑特殊情况
     if(head==null){
             head=newNode;
             tail=newNode;
             return true;
        }
        tail.next=newNode;
        tail=tail.next;
        return true;
    }

    //出队列(头部删除)
    public Integer poll(){
        //考虑特殊情况1.链表为空 2.只有一个元素
        if(head==null){
            return null;
        }
        int ret=head.val;
        if(head.next==null){
            head=null;
            return ret;
        }
        head=head.next;
        return ret;
    }

    //取队列首部元素
    public Integer peek(){
        if(head==null){
            return null;
        }
        return head.val;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值