栈和队列——算法笔记

本文首发在我的个人博客:https://jlice.top/p/7d4wx/。欢迎大家前去参观,么么哒~

链表

链表可以方便地实现以下操作:

从表头添加元素

https://jlice-top.oss-cn-beijing.aliyuncs.com/40f6f192002211e99952509a4c21c90b.png

Node tmp = front;
front = new Node();
front.value = item;  // item为添加的元素
front.next = tmp;

考虑边界情况,当链表为空添加元素时的情况,需调整rear:

https://jlice-top.oss-cn-beijing.aliyuncs.com/4170d36e002211e9b5f6509a4c21c90b.png

if(rear==null)
    rear = front;

从表尾添加元素

https://jlice-top.oss-cn-beijing.aliyuncs.com/418f1f50002211e99f7f509a4c21c90b.png

Node tmp = rear;
rear = new Node();
rear.value = item;  // item为添加的元素
tmp.next = rear;

考虑边界情况,当链表为空添加元素时的情况,需调整front,同时舍弃tmp.next = rear;

https://jlice-top.oss-cn-beijing.aliyuncs.com/41a94814002211e9953e509a4c21c90b.png

if(front==null)
    front = rear;

从表头删除元素

https://jlice-top.oss-cn-beijing.aliyuncs.com/41c4239c002211e9b211509a4c21c90b.png

T tmp = front.value;
front = front.next;

考虑边界情况,当链表仅剩一个元素删除时,需调整rear:

https://jlice-top.oss-cn-beijing.aliyuncs.com/41df2ce2002211e9984d509a4c21c90b.png

if(front==null)
    rear = null;

基于栈的特点,可以选择从表头添加元素,从表头删除元素,使用链表实现栈的代码如下:

public class Stack<T> {
    private class Node{
        T value;
        Node next;
    }
    private Node front;
    private int n;
    public void push(T item) {
        Node tmp = front;
        front = new Node();
        front.value = item;
        front.next = tmp;
        n++;
    }
    public T pop() {
        T tmp = front.value;
        front = front.next;
        n--;
        return tmp;
    }
    public int size() {
        return n;
    }
    public boolean isEmpty() {
        return front == null;
    }
}

队列

基于队列的特点,可以选择从表尾添加元素,从表头删除元素,使用链表实现队列的代码如下:

public class Queue<T>{
    private class Node{
        T value;
        Node next;
    }
    private Node front;
    private Node rear;
    private int n;
    public void enqueue(T item) {
        Node tmp = rear;
        rear = new Node();
        rear.value = item;
        if(tmp==null)
            front = rear;
        else
            tmp.next = rear;
        n++;
    }
    public T dequeue() {
        T tmp = front.value;
        front = front.next;
        if(front==null)
            rear = null;
        n--;
        return tmp;
    }
    public int size() {
        return n;
    }
    public boolean isEmpty() {
        return front == null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值