[算法与数据结构]使用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);
		}
	}
}

posted on 2020-08-20 00:04  coding_gaga  阅读(163)  评论(0编辑  收藏  举报

导航