码迷,mamicode.com
首页 > 其他好文 > 详细

Stack实现

时间:2017-10-28 20:27:24      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:imp   min   public   display   stack   obj   index   分享   lap   

栈的三种操作算法很简单

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

 

Stack实现

标签:imp   min   public   display   stack   obj   index   分享   lap   

原文地址:http://www.cnblogs.com/dgzhangning/p/7649609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!