• Stack实现


    栈的三种操作算法很简单

    STACK-EMPTY(S)

    1 if S.top == 0

    2    return TRUE

    3 else return FALSE

    PUSH(S, x)

    1 S.top = S.top + 1

    2 S[S.top] = x

    POP(S)

    1 if STACK-EMPTY(S)

    2   error "underflow"

    3 else S.top = S.top - 1

    4  return S[S.top + 1]

    Stack Java实现

     1 package hello;
     2 
     3 import java.util.Arrays;
     4 
     5 public class TStack<E> {
     6     private int capacity = 10;
     7     private int capacityIncrement = 10;
     8     private int elementCount = 0;
     9     private Object[] elementData;
    10 
    11     public TStack(){
    12         this.elementData = new Object[capacity];
    13     }
    14 
    15     public boolean empty(){
    16         return size() == 0;
    17     }
    18 
    19     public E push(E item){
    20         ensureCapacity(elementCount + 1);
    21         this.elementData[elementCount++] = item;
    22         return item;
    23     }
    24 
    25     public E pop(){
    26         E top = (E)this.elementData[elementCount-1];
    27         removeElement(elementCount-1);
    28         return top;
    29     }
    30 
    31     public int size(){
    32         return elementCount;
    33     }
    34 
    35     private void ensureCapacity(int minCapacity){
    36         if(minCapacity - this.elementData.length > 0){
    37             grow();
    38         }
    39     }
    40 
    41     private void grow(){
    42         int newCapacity = this.elementData.length + this.capacityIncrement;
    43         this.elementData = Arrays.copyOf(this.elementData, newCapacity);
    44     }
    45 
    46     private void removeElement(int index){
    47         if (index >= this.elementCount){
    48             throw new ArrayIndexOutOfBoundsException();
    49         }
    50         elementCount--;
    51         this.elementData[elementCount] = null;
    52     }
    53 
    54     public static void main(String[] args){
    55         TStack<Integer> s = new TStack<>();
    56         for (int i = 0; i < 100; i++){
    57             s.push(i);
    58         }
    59         int n = s.size();
    60         for (int i = 0; i < n; i++) {
    61             System.out.println(s.pop());
    62         }
    63     }
    64 }
    View Code
  • 相关阅读:
    linux基础名词
    计算机基础
    c++ 构造函数
    c++ stdafx.h、targetver.h文件
    centos7初步命令
    mysql 操作表的语句
    后台返回API数据格式
    nginx相关知识
    js复制内容到剪贴板格式化粘贴到excel中
    PHP开启错误提示
  • 原文地址:https://www.cnblogs.com/dgzhangning/p/7649609.html
Copyright © 2020-2023  润新知