来源:互联网 发布:淘宝网针织衫开衫短款 编辑:程序博客网 时间:2024/05/20 16:44

栈的实现:

/** * 顺序表实现的栈 * @author Administrator * * @param <T> */public class MyArrStack<T> {private int size; // 栈中存放放最多元素个数private int top; // 栈顶位置private T[] items; // 基础数组@SuppressWarnings("unchecked")public MyArrStack(int size) {this.size = size;top = -1;items = (T[]) new Object[size];}public void clear() {top = -1;}public int size() {return size;}public boolean isEmpty() {return size() == 0;}@SuppressWarnings("unchecked")public boolean push(T item) {if (top == size - 1) { // 栈满的时候T[] old = items;items = (T[]) new Object[size * 2 + 1];for (int i = 0; i < old.length; i++) {items[i] = old[i];}size = size * 2 + 1;}items[++top] = item; // 修改栈顶位置,新元素压栈size++;return true;}public T pop() {if (top == -1) {throw new java.util.NoSuchElementException();} else {T item = items[top--];// 栈顶元素出栈,修改栈顶位置size--;return item;}}public T top(T item) {if (top == -1) {throw new java.util.NoSuchElementException();} else {item = items[top];return item;}}}

链表实现栈:

/** * 栈的链表实现 * @author Administrator * * @param <T> */public class MyLinkedStack<T> {private static class Node<T> {public Node(T item, Node<T> next) {this.data = item;this.next = next;}public T data;public Node<T> next;}private int size;private Node<T> top;public MyLinkedStack() {top = null;size = 0;}public void clear() {while (top != null) {final Node<T> tmp = top.next;top.data = null; //help gctop.next = null;top = tmp;}size = 0;}public int size() {return size;}public boolean isEmpty() {return size() == 0;}public boolean push(T item) {Node<T> node = new Node<T>(item, top);top = node;size++;return true;}/** *   * @return 返回栈顶元素且删除 */public T pop() {if (size() == 0) {throw new java.util.NoSuchElementException();}T item = top.data;final Node<T> tmp = top.next;top.data = null;top.next = null;top = tmp;size--;return item;}public T top() {if (size() == 0) {throw new java.util.NoSuchElementException();}final T item = top.data;return item;}}


0 0
原创粉丝点击