数组实现栈
import java.util.Arrays;
class Mystack<T> {
//实现栈的数组
private Object[] stack;
//栈顶元素
private int top;
Mystack() {
//初始容量为10
stack = new Object[10];
}
//判断是否为空
public boolean isEmpty() {
return top == 0;
}
//返回栈顶元素
public T peek() {
if (top>0){
return (T) stack[top-1];
}
return null;
}
public void push(T t) {
expandCapacity(top+1);
stack[top]=t;
top++;
}
//出栈
public T pop() {
T t=peek();
if (top>0){
stack[top-1]=null;
top--;
}
return t;
}
//扩大容量
public void expandCapacity(int size) {
int len=stack.length;
if (size>len){
size=size*3/2+1;
stack=Arrays.copyOf(stack,size);
}
}
public static void main(String[] args) {
Mystack<String> stack = new Mystack<>();
System.out.println(stack.peek());
System.out.println(stack.isEmpty());
stack.push("java");
stack.push("is");
stack.push("beautiful");
stack.push("language");
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.peek());
}
}
链表实现栈
class ListStack<T> {
//定义链表
class Node<T> {
public T t;
public Node next;
}
public Node<T> head;
//构造函数初始化头指针
ListStack() {
head = null;
}
//入栈
public void push(T t) {
if (t == null) {
throw new NullPointerException("参数不能为空");
}
if (head == null) {
head = new Node<T>();
head.t = t;
head.next = null;
} else {
Node<T> temp = head;
head = new Node<>();
head.t = t;
head.next = temp;
}
}
//出栈
public T pop() {
if (head == null) {
return null;
}
T t = head.t;
head = head.next;
return t;
}
//取栈顶元素
public T peek() {
if (head == null) {
return null;
}
T t = head.t;
return t;
}
//栈空
public boolean isEmpty() {
if (head == null)
return true;
else
return false;
}
public static void main(String[] args) {
ListStack stack = new ListStack();
System.out.println(stack.isEmpty());
stack.push("Java");
stack.push("is");
stack.push("beautiful");
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
}
}
linkedList实现栈
public class LinkedListStack<T> {
private LinkedList<T> ll = new LinkedList<>();
//入栈
public void push(T t) {
ll.addFirst(t);
}
//出栈
public T pop() {
return ll.removeFirst();
}
//栈顶元素
public T peek() {
T t = null;
//直接取元素会报异常,需要先判断是否为空
if (!ll.isEmpty())
t = ll.getFirst();
return t;
}
//栈空
public boolean isEmpty() {
return ll.isEmpty();
}
public static void main(String[] args) {
LinkedListStack<String> stack = new LinkedListStack();
System.out.println(stack.isEmpty());
System.out.println(stack.peek());
stack.push("java");
stack.push("is");
stack.push("beautiful");
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
}
}