java中Stack的问题
请问如何在不调用任何package的情况下(java.util.*)在一个STACK的类里面做到以下的事情1.导入一个OBJECT并且把它加到STACK里面去2.在POP...
请问如何在不调用任何package的情况下(java.util.*)在一个STACK的类里面做到以下的事情
1.导入一个OBJECT并且把它加到STACK里面去
2.在POP这个method里返回stack顶部的值并且把它删掉
3.新建一个boolean,测试stack里面是否为空 展开
1.导入一个OBJECT并且把它加到STACK里面去
2.在POP这个method里返回stack顶部的值并且把它删掉
3.新建一个boolean,测试stack里面是否为空 展开
3个回答
展开全部
闲着实在无聊......
写了个简单的双链表实现Stack。未引用任何包。
public class Main {
public static void main(String[] args) {
Stack s = new Stack();
s.put("abc");//压栈
s.put("def");//压栈
s.put("ghi");
System.out.println(s.pop());//出栈
System.out.println(s.isEmpty());//判断栈是否为空
System.out.println(s.pop());
System.out.println(s.isEmpty());
System.out.println(s.pop());
System.out.println(s.isEmpty());
}
}
class Stack {
private Node root = new Node();
private Node top = root;
public Object pop() {
if(top != null) {
Object value = top.getValue();
top = top.getPrevious();
return value;
} else {
return null;
}
}
public void put(Object value) {
Node n = new Node(top, value);
top.setNext(n);
top = n;
}
public boolean isEmpty() {
return top.getPrevious() == null;
}
}
class Node {
private Node next;
private Object value;
private Node previous;
public Node() {
}
public Node(Node previous, Object value) {
this.previous = previous;
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
}
写了个简单的双链表实现Stack。未引用任何包。
public class Main {
public static void main(String[] args) {
Stack s = new Stack();
s.put("abc");//压栈
s.put("def");//压栈
s.put("ghi");
System.out.println(s.pop());//出栈
System.out.println(s.isEmpty());//判断栈是否为空
System.out.println(s.pop());
System.out.println(s.isEmpty());
System.out.println(s.pop());
System.out.println(s.isEmpty());
}
}
class Stack {
private Node root = new Node();
private Node top = root;
public Object pop() {
if(top != null) {
Object value = top.getValue();
top = top.getPrevious();
return value;
} else {
return null;
}
}
public void put(Object value) {
Node n = new Node(top, value);
top.setNext(n);
top = n;
}
public boolean isEmpty() {
return top.getPrevious() == null;
}
}
class Node {
private Node next;
private Object value;
private Node previous;
public Node() {
}
public Node(Node previous, Object value) {
this.previous = previous;
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询