java泛型实现栈_[算法与数据结构]使用Java泛型实现栈
题解
1 实现内部类node
2 维护top为头节点的链表
3 操作
操作1:push()
操作2: pop()
操作3: isEmpty()
代码
package Exam;
class MyStackStruct {
private class Node {
U val;
Node next;
Node() {
this.val = null;
this.next = null;
}
Node(U val, Node next) {
this.val = val;
this.next = next;
}
boolean isEmptyNode() {
return this.val == null && this.next == null;
}
}
private Node top = new Node<>();
public void push(T val) {
top = new Node(val, top);
}
public T pop() {
T val = null;
if (!top.isEmptyNode()) {
val = top.val;
top = top.next;
}
return val;
}
public boolean isEmpty() {
return top.isEmptyNode();
}
}
public class MyStack {
public static void main(String[] args) {
MyStackStruct stack = new MyStackStruct<>();
stack.push(1);
stack.push(2);
while (!stack.isEmpty()) {
int val = stack.pop();
System.out.println(val);
}
}
}
题解 1 实现内部类node 2 维护top为头节点的链表 3 操作 操作1:push() 操作2: pop() 操作3: isEmpty() 代码 package Exam; class MyStackStruct { private class Node { U val; Node next; Node() { this.val = null; this.next = null; } Node(U val, Node next) { this.val = val; this.next = next; } boolean isEmptyNode() { return this.val == null && this.next == null; } } private Node top = new Node<>(); public void push(T val) { top = new Node(val, top); } public T pop() { T val = null; if (!top.isEmptyNode()) { val = top.val; top = top.next; } return val; } public boolean isEmpty() { return top.isEmptyNode(); } } public class MyStack { public static void main(String[] args) { MyStackStruct stack = new MyStackStruct<>(); stack.push(1); stack.push(2); while (!stack.isEmpty()) { int val = stack.pop(); System.out.println(val); } } }