?? stack.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(); // 獲取頭節(jié)點數(shù)據(jù)
head = head.getNext(); // 移除頭節(jié)點
count--;
return data;
}
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("堆棧為空!");
}
return head.getData(); // 返回頭節(jié)點數(shù)據(jù)
}
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());
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -