Java实现栈
模仿jdk源码,实现栈的几种操作:isEmpty(); clear(); length(); push(); pop();
我们首先定义栈的接口:
1 public interface MyStack<T> { 2 /** 3 * 判断栈是否为空 4 */ 5 boolean isEmpty(); 6 /** 7 * 清空栈 8 */ 9 void clear(); 10 /** 11 * 栈的长度 12 */ 13 int length(); 14 /** 15 * 数据入栈 16 */ 17 boolean push(T data); 18 /** 19 * 数据出栈 20 */ 21 T pop(); 22 }
下面是栈的具体实现,第一种实现使用数组存储,即底层使用数组:
1 public class MyArrayStack<T> implements MyStack<T> { 2 private Object[] objs = new Object[16]; 3 private int size = 0; 4 5 @Override 6 public boolean isEmpty() { 7 return size == 0; 8 } 9 10 @Override 11 public void clear() { 12 // 将数组中的数据置为null, 方便GC进行回收 13 for (int i = 0; i < size; i++) { 14 objs[size] = null; 15 } 16 size = 0; 17 } 18 19 @Override 20 public int length() { 21 return size; 22 } 23 24 @Override 25 public boolean push(T data) { 26 // 判断是否需要进行数组扩容 27 if (size >= objs.length) { 28 resize(); 29 } 30 objs[size++] = data; 31 return true; 32 } 33 34 /** 35 * 数组扩容 36 */ 37 private void resize() { 38 Object[] temp = new Object[objs.length * 3 / 2 + 1]; 39 for (int i = 0; i < size; i++) { 40 temp[i] = objs[i]; 41 objs[i] = null; 42 } 43 objs = temp; 44 } 45 46 @SuppressWarnings("unchecked") 47 @Override 48 public T pop() { 49 if (size == 0) { 50 return null; 51 } 52 return (T) objs[--size]; 53 } 54 55 @Override 56 public String toString() { 57 StringBuilder sb = new StringBuilder(); 58 sb.append("MyArrayStack: ["); 59 for (int i = 0; i < size; i++) { 60 sb.append(objs[i].toString()); 61 if (i != size - 1) { 62 sb.append(", "); 63 } 64 } 65 sb.append("]"); 66 return sb.toString(); 67 } 68 }
另一种使用链表作为底层存储
1 public class MyLinkedStack<T> implements MyStack<T> { 2 /** 3 * 栈顶指针 4 */ 5 private Node top; 6 /** 7 * 栈的长度 8 */ 9 private int size; 10 11 public MyLinkedStack() { 12 top = null; 13 size = 0; 14 } 15 16 @Override 17 public boolean isEmpty() { 18 return size == 0; 19 } 20 21 @Override 22 public void clear() { 23 top = null; 24 size = 0; 25 } 26 27 @Override 28 public int length() { 29 return size; 30 } 31 32 @Override 33 public boolean push(T data) { 34 Node node = new Node(); 35 node.data = data; 36 node.next = top; 37 // 改变栈顶指针 38 top = node; 39 size++; 40 return true; 41 } 42 43 @Override 44 public T pop() { 45 if (top != null) { 46 Node node = top; 47 // 改变栈顶指针 48 top = top.next; 49 size--; 50 return node.data; 51 } 52 return null; 53 } 54 55 /** 56 * 将数据封装成结点 57 */ 58 private final class Node { 59 private Node next; 60 private T data; 61 } 62 }