stack.java

来自「这里面包含有栈」· Java 代码 · 共 60 行

JAVA
60
字号
package org.huhuiyu.datastructures;

public class Stack<T> {
	private Node<T> head = null;
	private int count = 0;

	public Stack() {
	}

	public void push(T data) {
		// 添加到头的位置
		Node<T> add = new Node<T>(data);
		add.setNext(head);
		head = add;
		count++;
	}

	public T pop() {
		if (isEmpty()) {
			throw new IllegalStateException("堆栈为空!");
		}
		T data = head.getData(); // 获取头节点数据
		head = head.getNext(); // 移除头节点
		count--;
		return data;
	}

	public T peek() {
		if (isEmpty()) {
			throw new IllegalStateException("堆栈为空!");
		}
		return head.getData(); // 返回头节点数据
	}

	public void clear() {
		head = null;
		count = 0;
	}

	public boolean isEmpty() {
		return count == 0;
	}

	public int size() {
		return count;
	}

	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<Integer>();
		for (int i = 1; i < 10; i++) {
			stack.push(i);
		}
		System.out.println("size():"+stack.size());
		while (!stack.isEmpty()) {
			System.out.println(stack.pop());
		}
		System.out.println("size():"+stack.size());
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?