zoukankan      html  css  js  c++  java
  • [算法与数据结构]使用Java泛型实现栈

    题解

    1 实现内部类node
    2 维护top为头节点的链表
    3 操作
    操作1:push()
    操作2: pop()
    操作3: isEmpty()

    代码

    package Exam;
    
    class MyStackStruct<T> {
    	private class Node<U> {
    		U val;
    		Node<U> next;
    
    		Node() {
    			this.val = null;
    			this.next = null;
    		}
    
    		Node(U val, Node<U> next) {
    			this.val = val;
    			this.next = next;
    		}
    
    		boolean isEmptyNode() {
    			return this.val == null && this.next == null;
    		}
    	}
    
    	private Node<T> top = new Node<>();
    
    	public void push(T val) {
    		top = new Node<T>(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<Integer> stack = new MyStackStruct<>();
    		stack.push(1);
    		stack.push(2);
    		while (!stack.isEmpty()) {
    			int val = stack.pop();
    			System.out.println(val);
    		}
    	}
    }
    
    
  • 相关阅读:
    代理
    博客园主题
    JS_1
    脚本语言
    Hadoop生态体系
    Hadoop序列化程序报错
    46. 全排列
    1038 Recover the Smallest Number (30分)
    1064 Complete Binary Search Tree (30分)
    1034 Head of a Gang (30分)
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/13532691.html
Copyright © 2011-2022 走看看