⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stack.java

📁 这里面包含有栈
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -