zoukankan      html  css  js  c++  java
  • Java栈的简单实现

     * 数据结构与算法Java实现 栈
     * 
     * @author 小明
     *
     */
    public class MyStack {
        private Node top;// 头指针
        int size;// 长度
    
        public MyStack() {
            top = null;
            size = 0;
        }
    
        // 进栈函数
        public void push(Node node) {
            if (size == 0) {// 栈为空时
                top = node;
                size++;
            } else {// 栈不为空时
                node.setNext(top);
                top=node;
                size++;
            }
        }
        //出栈函数
        public void pop() throws IndexException {
            if(size==0) {
                throw new IndexException("索引错误!");
            }else {
                top=top.getNext();//出栈
                size--;
            }
        }
        @Override
        public  String toString() {
            String str=" ";
            Node temp=top;
            while(temp!=null){
                str+=temp.getElement()+" ";
                temp=temp.getNext();
            }
            str="["+str+" ]";
            return str;
        }
        public static void main(String[] args) throws IndexException {
            MyStack mystack=new MyStack();
            mystack.push(new Node(0));
            mystack.push(new Node(1));
            mystack.push(new Node(2));
            mystack.pop();
            mystack.push(new Node(3));
            System.out.println(mystack);
        }
    }
    
    class Node<T> {
        private T element;// 元素
        private Node next;// 后继
    
        public Node(T element) {// 初始化函数
            this.element = element;
            this.next = null;
        }
    
        public void setNext(Node node) {
            this.next = node;
        }
    
        public Node getNext() {
            return next;
        }
    
        public T getElement() {
            return element;
        }
    }
    
    /*
     * 索引异常类
     */
    class IndexException extends Exception {
        public IndexException() {
    
        }
    
        public IndexException(String s) {
            super(s);
        }
    }
  • 相关阅读:
    DirectShow自带实例StillCap在回调函数里实现抓图并保存为文件
    x264 VS2008下编译成功
    yuy2_to_i420,yuyv_to_i420
    x264源码阅读
    oracle 归档日志开启、关闭及删除归档日志
    TOMCAT设置JVM
    linux root 操作oracle命令
    struts2 标签判断list是否为空
    linux下mysql 5.5配置
    RHEL 6 下VNC Server 的安装配置
  • 原文地址:https://www.cnblogs.com/SAM-CJM/p/9307278.html
Copyright © 2011-2022 走看看