数据结构--链表实现栈和队列

引入

数据结构--数组实现栈和队列-CSDN博客这篇文章中我们已经用数组实现了栈和队列,那么我们再练习一下链表实现吧!o(* ̄▽ ̄*)ブ

既然是链表,那么前提给出一个创建节点的封装类:

java 复制代码
public class Node {
    int data;
    Node next;
    public Node(){
        //空构造函数
    }
    public Node(int data){
        this.data=data;
        this.next=null;
    }
    @Override
    public String toString() {
        return (this.next == null) ?  this.data + " " :  this.data + " " + this.next.toString();
    }
}

1.用链表实现入栈和出栈

java 复制代码
public class ListStack {
  private Node top;
  //入栈(链表)
  public void put(int value){
      Node newNode=new Node(value);
      newNode.next=top;
      top=newNode;
      System.out.println("入栈成功!");
  }
  //出栈
    public void get(){
      if(top==null){
          System.out.println("栈已经空了!");
          return;
      }
        System.out.println(top.data);
        top=top.next;
    }
}

一个测试Main:

java 复制代码
public class Test {
    public static void main(String[] args) {
        ListStack stack=new ListStack();
        stack.put(4);
        stack.put(3);
        stack.put(6);
        stack.put(1);

        stack.get();
        stack.get();
        stack.get();
        stack.get();
        stack.get();

    }
}

得到结果:

2.用链表实现入队和出队

java 复制代码
public class ListQueue {
    private Node left;
    private Node right;

    public void put(int value){
        Node newNode=new Node(value);
        if(left==null&&right==null){
            left=newNode;
            right=newNode;
            System.out.println("入队成功");
            return;
        }
        left.next=newNode;
        left=newNode;
        System.out.println("入队成功");
    }
    public void get(){
        if(right==null){
            System.out.println("队列已空!");
            return;
        }
        System.out.println(right.data);
        right=right.next;

    }
}

得到结果:

相关推荐
dragoooon344 分钟前
[优选算法专题九.链表 ——NO.53~54合并 K 个升序链表、 K 个一组翻转链表]
数据结构·算法·链表
松涛和鸣5 分钟前
22、双向链表作业实现与GDB调试实战
c语言·开发语言·网络·数据结构·链表·排序算法
h***04772 小时前
SpringBoot(7)-Swagger
java·spring boot·后端
v***91304 小时前
Spring boot创建时常用的依赖
java·spring boot·后端
代码or搬砖6 小时前
MyBatisPlus讲解(二)
java·mybatis
lcu1116 小时前
Java 学习42:抽象
java
Mr.朱鹏6 小时前
RocketMQ安装与部署指南
java·数据库·spring·oracle·maven·rocketmq·seata
雨中飘荡的记忆6 小时前
Spring表达式详解:SpEL从入门到实战
java·spring
Coder-coco6 小时前
个人健康管理|基于springboot+vue+个人健康管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·mysql·论文
5***26227 小时前
Spring Boot问题总结
java·spring boot·后端