zoukankan      html  css  js  c++  java
  • 栈/队列实例

    (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;
    }
    }

  • 相关阅读:
    Prototype源码浅析——String部分(四)之补充
    改造alert的引发的争论【基本类型与引用类型】
    Eclipse rcp 窗口激活
    Eclipse statusLine 加入进度信息
    线的匹配
    python 文本搜索
    Eclipse rcp 编辑器行号显示
    CDT重建索引
    Eclipse rcp 数据存储
    CTabFolder 最大最小化
  • 原文地址:https://www.cnblogs.com/muliu/p/6835015.html
Copyright © 2011-2022 走看看