LinkedStack的底层实现

 



package zy813ture; import java.util.EmptyStackException; public class MyLinkedStack1 { private Node top = new Node(); private class Node { private Object data; private Node next; } /* * public MyLinkedStack1(){ * * } */ public boolean isEmpty() { return top.next == null; } public Object peek() {// 查看堆栈顶部的对象,但不从堆栈中移除它。 if (top.next == null) { throw new EmptyStackException(); } return top.next.data; } public Object poll() {// 移除堆栈顶部的对象,并作为此函数的值返回该对象 if (top.next == null) { throw new EmptyStackException(); } Node node = top.next;// 定义移除的节点node top.next = node.next;// 移除 // size--; return node.data; } public Object push(Object item) {// 把项压入堆栈顶部。 Node node = new Node();// 定义一个node接收item node.data = item; node.next = top.next;// 让node连接到top.next top.next = node; // size++; return item; } public Object search(Object item) {// 查找对象在堆栈中的位置,以 1 为基数 Node node = top.next; int i = 0; while (node != null) { i++; if (item == null ? item == node.data : item.equals(node.data)) { return i; } node = node.next; // i++; } return -1; } public static void main(String[] args) { MyLinkedStack1 mk = new MyLinkedStack1(); mk.push("ab1"); mk.push("ab2"); mk.push("ab3"); System.out.println(mk.search("ab3")); // System.out.println(mk.peek()); System.out.println(mk.poll()); } }

  

原文地址:https://www.cnblogs.com/ysg520/p/9471668.html