栈,先进后出
push
public void push(E data){
Node<E> node = new Node<>(data);
node.next = head.next;
head.next = node;
}
pop
public E pop(){
if (isEmpty()){
throw new RuntimeException("栈空");
}
Node<E> node = head.next;
head.next = node.next;
return node.data;
}
isEmpty
public boolean isEmpty(){
return head.next == null;
}
总览
package com.collection;
public class LinkStack<E> {
private final Node<E> head = new Node<>(null);
public void push(E data){
Node<E> node = new Node<>(data);
node.next = head.next;
head.next = node;
}
public E pop(){
if (isEmpty()){
throw new RuntimeException("栈空");
}
Node<E> node = head.next;
head.next = node.next;
return node.data;
}
public boolean isEmpty(){
return head.next == null;
}
private static class Node<E> {
private E data;
private Node<E> next;
public Node(E data) {
this.data = data;
}
}
}
测试
package com.collection;
public class Main {
public static void main(String[] args) {
LinkStack<String> stack = new LinkStack<>();
stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}