用Java实现栈

其实在一开始,这个小实验是我用来测试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;
	}
}

运行结果截图:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值