• 链栈


    public class LinkedStack {
    
    	Node head = new Node();
    	boolean empty() {
    		return head.next == null;
    	}
    	
    	void push(int e) {
    		Node n = new Node(e);
    		n.next = head.next;
    		head.next = n;
    	}
    	
    	int[] pop() {
    		int[] arr = new int[2];
    		if(empty()) {
    			arr[0] = 0;
    			return arr;
    		}
    		arr[0] = 1;
    		arr[1] = head.next.data;
    		head.next = head.next.next;
    		return arr;
    	}
    	
    	int[] top() {
    		int[] arr = new int[2];
    		if(empty()) {
    			arr[0] = 0;
    			return arr;
    		}
    		arr[0] = 1;
    		arr[1] = head.next.data;
    		
    		return arr;
    	}
    	
    	void display() {
    		Node p = head.next;
    		while(p != null) {
    			if(p.next != null)
    				System.out.print(p.data + "->");
    			else 
    				System.out.println(p.data);
    			p = p.next;
    		}
    	}
    	
    	public static void main(String[] args) {
    		LinkedStack ss = new LinkedStack();
    		System.out.println(ss.empty());
    		ss.push(2);
    		ss.push(3);
    		ss.display();
    		ss.pop();
    		ss.display();
    		ss.push(1);
    		ss.push(2);
    		ss.display();
    		ss.pop();
    		ss.push(4);
    		ss.display();
    		ss.top();
    		ss.display();
    
    	}
    
    }
    
    class Node {
    	int data;
    	Node next;
    	Node() {}
    	Node(int e) {
    		data = e;
    	}
    	
    }
    


    结果:

    true
    3->2
    2
    2->1->2
    4->1->2
    4->1->2
    


  • 相关阅读:
    centos 7常用需求
    python处理mysql的一些用法
    python下的queue
    2017-1-17不错的模块和工具
    wordpress钩子和钩子函数
    python中字典的使用
    linux下查看系统信息
    apk安全测试思路
    rhel 5.8 and 6.4 yum配置
    分布式文件系统
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/7242135.html
Copyright © 2020-2023  润新知