Java中栈的代码实现

用数组来实现栈数据结构

import java.util.Arrays;

//用数组实现栈数据结构
public class MyStack<E> {
	private Object[] stack;
	private int size;// 数组中存储元素的个数

	public MyStack() {
		stack = new Object[10];// 初始长度为10
	}

	// 判断栈是否为空
	public boolean isEmpty() {
		return size == 0;
	}

	public E peek() {
		if (isEmpty()) {
			return null;
		} else {
			return (E) stack[size - 1];
		}
	}

	public E pop() {
		E e = peek();
		if(e == null) {
			System.out.println("栈中已经没有元素了!!");
			return null;
		}
		stack[size - 1] = null;
		size--;
		return e;
	}

	public E push(E item) {
		ensureCapacity(size + 1);
		stack[size++] = item;//很有意思的一行代码J:size +1 了,数据存在下标为size的位置上。
		return item;
	}

	public void ensureCapacity(int size) {
		int len = stack.length;
		if (size > len) {
			int newLen = 10;
			stack = Arrays.copyOf(stack, newLen);
		}
	}

}

用链表来实现栈的数据结构

public class Node<E> {
	E data;
	Node next;

	public Node(E data) {
		this.data = data;
	}

}
public class Stack<E> {
	Node<E> top = null;

	public boolean isEmpty() {
		return top == null;
	}

	public void push(E data) {
		Node<E> tmp = new Node<E>(data);
		tmp.next = top;
		top = tmp;
	}

	public E pop() {
		if (isEmpty()) {
			return null;
		}
		E data = top.data;
		top = top.next;
		return data;
	}

	public E peek() {
		if (isEmpty()) {
			return null;
		}
		return top.data;
	}
}
发布了58 篇原创文章 · 获赞 0 · 访问量 998

猜你喜欢

转载自blog.csdn.net/Mason97/article/details/104360165