实现代码
class Node<T> {
private T data;
private Node<T> next;
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
public Node() {
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getNext() {
return this.next;
}
public void setNext(Node<T> next) {
this.next = next;
}
}
class LinkStack<N> {
private Node<N> top;
private int size=0;
public LinkStack(Node<N> head) {
this.top = head;
}
public LinkStack() {
super();
}
public Node<N> peek() {
return top;
}
public void setHead(Node<N> head) {
this.top = head;
}
public int getSize() {
return size;
}
public void push(N data){
Node<N> node = new Node<>(data,null);
if(isEmpty()){
top = node;
size++;
}else{
node.setNext(top);
top = node;
size++;
}
}
public N pop(){
if(!isEmpty()){
N data = top.getData();
top = top.getNext();
size--;
return data;
}else{
throw new RuntimeException("栈是空的!");
}
}
public boolean isEmpty(){
return size == 0;
}
}
测试代码
public class LinkedStackTest {
public static void main(String[] args) {
LinkStack<Integer> stack = new LinkStack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
System.out.println("入栈顺序: 10->20->30->40->50");
System.out.print("出栈顺序:");
while(!stack.isEmpty()) {
System.out.printf(" %d ",stack.pop());
}
}
}
实现截图
