Eason-S

导航

java栈的实现

可以采用数组与链表两种方法来实现栈。

 1、用数组实现栈

 1 import java.util.Arrays;
 2 public class MyStack<E>{
 3     private Object[] stack;
 4     private int size; //数组中存储元素的个数
 5     public MyStack(){
 6         stack = new Object[10]; //初始化长度为10
 7     }
 8     //判断堆栈是否为空
 9     public boolean isEmpty(){
10         return size == 0;
11     }
12 
13     public E peek(){
14         if(isEmpty()){
15             return null;
16         }
17         return(E) stack[size-1];
18     }
19 
20     public E pop(){
21         E e = peek();
22         stack[size-1] = null;
23         size--;
24         return e;
25     }
26 
27     public E push(E item){
28         ensureCapacity(size+1);
29         stack[size++] = item;
30         return item;
31     }
32 
33     //判断数组是否已满,若已满,则扩充数组空间
34     private void ensureCapacity(int size){
35         int len = stack.length;
36         if(size > len){//数组已满
37             int newLen = 10;//每次数组扩充的容量
38             stack = Arrays.copyOf(stack,newLen);
39         }
40     }
41 }

 2、用链表实现栈

 1 class Node{
 2     Node next = null;
 3     int data;
 4     public Node(int data){this.data = data;}
 5 }
 6 
 7 public class Stack<E>{
 8     Node<E> top = null;
 9 
10     public boolean isEmpty(){
11         return top == null;
12     }
13 
14     public void push(E data){
15         Node<E> newNode = new Node<E>(data);
16         newNode.next = top;
17         top = newNode;
18     }
19 
20     public E pop(){
21         if(this.isEmpty())
22             return null;
23         E data = top.data;
24         top = top.next;
25         return data;
26     }
27 
28     public E peek(){
29         if(isEmpty()){
30             return null;
31         }
32         return top.data;
33     }
34 }

 

posted on 2016-05-18 16:49  Eason_S  阅读(306)  评论(0编辑  收藏  举报