Node
package com.qyc.Stack;
public class Node<E> {
Node<E> next = null;
E date;
public Node(E date) {
super();
this.date = date;
}
}
Stack
package com.qyc.Stack;
public class MyStack<E> {
// top
Node<E> top = null;
// 判空
public boolean isEmpty() {
return top == null;
}
// 进栈
public void push(E data) {
Node<E> newNode = new Node<E>(data);
newNode.next = top;
top = newNode;
}
// 出栈
public E pop() {
if (isEmpty()) {
return null;
}
E data = top.date;
top = top.next;
return data;
}
// 显示栈顶data
public E peek() {
if (isEmpty()) {
return null;
}
return top.date;
}
}
测试
package com.qyc.Stack;
public class TestStack {
public static void main(String[] args) {
MyStack<Integer> myStack = new MyStack<>();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
System.out.println("栈顶" + myStack.peek());
System.out.println();
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
}
}
栈顶4
4
3
2
1