其实在一开始,这个小实验是我用来测试Java当中的变量引用的,由于较长时间没写Java项目了,而之前有弄过一段时间的C++,所以对Java的变量引用这一块有点不自信,就写了这么一个小程序来做一下实验。所以连函数名都不是Stack而是QuoteTest。这是一个简单的对栈数据结构的实现。
package Test;
public class QuoteTest {
private Node head;
private int length;
private Node node2 = new Node();
private Node node3 = new Node();
public QuoteTest(){
this.head = null;
this.length = 0;
}
public void push(Node node){
if(head == null){
head = node;
}else{
node3 = head;//这里node3是head的引用
while(node3.getNext()!=null){
node3 = node3.getNext();
}
node3.setNext(node);
}
}
public Node pop(){
if(head == null){
return null;
}else if(head.getNext()==null){
node2 = head;
head = null;
return node2;
}else{
node3 = head;
node2 = node3.getNext();
while(node2.getNext()!=null){
node3 = node3.getNext();
node2 = node3.getNext();
}
node3.setNext(null);
return node2;
}
}
public void GoThrough(){
if(head == null){
System.out.println("Empty");
}else{
System.out.print(head.getValue());
node3 = head;
while(node3.getNext()!=null){
node3 = node3.getNext();
System.out.print("-->"+node3.getValue());
}
System.out.println();
}
}
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
QuoteTest list = new QuoteTest();
QuoteTest list2 = new QuoteTest();
list.push(node1);
list.push(node2);
list.push(node3);
list.GoThrough();
list2.push(node4);
list2.push(node5);
list2.GoThrough();
list.push(node4);
list.GoThrough();
}
}
class Node{
private int number;
private Node next;
public Node(){
next = null;
number = 0;
}
public Node(int number){
this.number = number;
next = null;
}
public int getValue(){
return number;
}
public void setNext(Node node){
this.next = node;
}
public Node getNext(){//顺便检查不把null单独拿出来会不会报错
return next;
}
}
运行结果截图: