• 栈/队列实例


    (1)栈的实例:

     我们接下来通过链表的形式来创建栈,方便扩充。

    /**
    * Stack的特性:后进先出
    */
    public class Stack {
    public Node head;
    public Node current;

    public static void main(String[] args) {
    Stack stack = new Stack();
    stack.push(11);
    stack.push(12);
    stack.push(13);
    System.out.println(stack.pop().data);
    System.out.println(stack.pop().data);
    System.out.println(stack.pop().data);
    }

    public void push(int data) {
    if (head == null) {
    head = new Node(data);
    current = head;
    } else {
    Node node = new Node(data);
    node.pre = current;
    current = node;

    }
    }

    public Node pop() {
    if (current == null) {
    return null;
    }
    Node node = current;
    current = node.pre;
    return node;
    }
    }
    class Node {
    Node pre;
    int data;

    public Node(int data) {
    this.data = data;
    }
    }

    import java.util.LinkedList;
    import java.util.List;

    public class Queue {
    public Node1 head;
    public Node1 curent;

    public void add(int data) {
    if (head == null) {
    head = new Node1(data);
    curent = head;
    } else {
    curent.next = new Node1(data);
    curent = curent.next;
    }
    }

    // 方法:出队操作
    public int pop() throws Exception {
    if (head == null) {
    throw new Exception("队列为空");
    }

    Node1 node = head; // node结点就是我们要出队的结点
    head = head.next; // 出队之后,head指针向下移
    return node.data;

    }

    }

    class Node1 {
    Node1 next;
    int data;

    public Node1(int data) {
    this.data = data;
    }
    }

  • 相关阅读:
    springboot整合shiro进行权限管理
    多线程基础(一)
    面试杂谈(一)
    Spring循环依赖问题
    记一次电话面试的题目
    Jvm垃圾回收器(终结篇)
    Jvm垃圾回收器(算法篇)
    Jvm垃圾回收器(基础篇)
    Java内存模型探秘
    Jvm类的加载机制
  • 原文地址:https://www.cnblogs.com/muliu/p/6835015.html
Copyright © 2020-2023  润新知