码迷,mamicode.com
首页 > 其他好文 > 详细

LinkedStack的底层实现

时间:2018-08-13 23:51:48      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:data   object   next   equal   .data   throw   lin   str   empty   

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());

	}

}

  

LinkedStack的底层实现

标签:data   object   next   equal   .data   throw   lin   str   empty   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!