下压(LIFO)栈基础

两种栈的实现方式,一种是基于动态可调整数组大小的栈,一种是基于链表。用数组栈比较快速节约空间,用链栈插入删除比较高效(比动态数组占用空间多一些)

 1 import java.util.Iterator;
 2 
 3 public class ResizingArrayStack<Item> implements Iterable<Item> {
 4     
 5     private Item[] a = (Item[])new Object[1];  //栈元素
 6     private int N = 0;                         //元素数量
 7     
 8     
 9     public int size() {
10         return N;
11     }
12     
13     public boolean isEmpty() {
14         return N == 0;
15     }
16     
17     public void resize(int max) {
18 //将栈移动到一个大小为max的新数组
18 Item[] temp = (Item[])new Object[max]; 19 for(int i=0; i<N; i++) { 20 temp[i] = a[i]; 21 } 22 a = temp; 23 } 24 25 public void push(Item item) {
26 //将元素添加到栈顶
26 if(N == a.length) {//增倍条件--已满 27 resize(2*a.length);//增大数组空间(增加一倍) 28 } 29 a[N++] = item; 30 } 31 32 public Item pop() {
//从栈顶删除元素
33 Item item = a[--N]; 34 a[N] = null;//避免对象游离(保存一个不需要的对象的引用称为对象游离) 35 if(N>0 && N==a.length/4) {//缩小条件--空间为当前空间的1/4 36 resize(a.length/2);//缩小数组空间(缩小一半) 37 } 38 return item; 39 } 40 41 @Override 42 public Iterator<Item> iterator() { 43 return new ReverseArrayIterator(); 44 } 45 private class ReverseArrayIterator implements Iterator<Item>{ 46 private int i = N; 47 48 @Override 49 public boolean hasNext() { 50 return i > 0; 51 } 52 53 @Override 54 public Item next() { 55 return a[--i]; 56 } 57 } 58 59 }
 1 import java.util.Iterator;
 2 
 3 public class Stack<Item> implements Iterable<Item> {
 4     
 5     private Node first;  //栈顶(最近添加的元素)
 6     private int N;       //元素数量
 7     
 8     private class Node{
//定义结点的嵌套类
9 Item item; 10 Node next; 11 } 12 13 public boolean isEmpty() { 14 return N == 0;//或者 first == null; 15 } 16 17 public int size() { 18 return N; 19 } 20 21 public void push(Item item) { 22 //从栈顶添加元素 23 Node oldFirst = first; 24 first = new Node(); 25 first.item = item; 26 first.next = oldFirst; 27 N++; 28 } 29 30 public Item pop() { 31 //从栈顶删除元素 32 Item item = first.item; 33 first = first.next; 34 N--; 35 return item; 36 } 37 38 @Override 39 public Iterator<Item> iterator() { 40 return new ListIterator(); 41 } 42 43 private class ListIterator implements Iterator<Item>{ 44 45 private Node current = first; 46 47 @Override 48 public boolean hasNext() { 49 return current != null; 50 } 51 52 @Override 53 public Item next() { 54 Item item = current.item; 55 current = current.next; 56 return item; 57 } 58 59 } 60 61 }

 

posted @ 2018-01-29 13:14  dreamy_java  阅读(194)  评论(0编辑  收藏  举报