zoukankan      html  css  js  c++  java
  • 数据结构之栈

      1 package com.fz.song.stack;
      2 
      3 /**
      4  * Created by sfz on 2017/8/29.
      5  */
      6 public class MyStack {
      7 
      8     //长度
      9     private int size;
     10     //数组
     11     private int[] data;
     12     //栈顶
     13     private int top;
     14 
     15     public MyStack(int size) {
     16         this.size = size;
     17         data = new int[size];
     18         top = 0;
     19     }
     20 
     21     /**
     22      * 判断是否为空
     23      *
     24      * @return
     25      */
     26     public boolean isEmpty() {
     27         return 0 == top;
     28     }
     29 
     30     /**
     31      * 判满
     32      *
     33      * @return
     34      */
     35     public boolean isFull() {
     36         return (0 != size && size == top);
     37     }
     38 
     39 
     40     /**
     41      * 清空栈
     42      *
     43      * @return
     44      */
     45     public boolean cleanStack() {
     46         if (isEmpty()) {
     47             return false;
     48         } else {
     49             top = 0;
     50             return true;
     51         }
     52     }
     53 
     54     /**
     55      * 获取长度
     56      *
     57      * @return
     58      */
     59     public int length() {
     60         return top;
     61     }
     62 
     63 
     64     /**
     65      * 入栈
     66      *
     67      * @param elem
     68      * @return
     69      */
     70     public boolean push(int elem) {
     71 
     72         if (isFull()) {
     73             return false;
     74         } else {
     75             data[top] = elem;
     76             top++;
     77             return true;
     78         }
     79     }
     80 
     81     /**
     82      * 出栈
     83      *
     84      * @return
     85      */
     86     public int pop() throws Exception {
     87 
     88         if (isEmpty()) {
     89             throw new Exception("当前栈为空");
     90         } else {
     91             top--;
     92             int val = data[top];
     93             return val;
     94         }
     95     }
     96 
     97     /**
     98      * 遍历栈元素
     99      */
    100     public void each() {
    101         for (int i = 0; i < top; i++) {
    102             System.out.print(data[i] + "  ");
    103         }
    104         System.out.println("");
    105     }
    106 
    107 }
  • 相关阅读:
    linux下将一个大的文件拆分成若干小文件
    linux远程下载文件 的两种方法之 ftp命令和scp命令
    Python正则表达式的七个使用范例
    isinstance()和type()
    “可变的”tuple
    Tomcat常用面试题
    Tomcat常用配置详解
    Java工程师该如何编写高效代码?
    收集100条实用的网络知识
    MySQL 19个规则数据库设计总结
  • 原文地址:https://www.cnblogs.com/songfahzun/p/7446918.html
Copyright © 2011-2022 走看看