您当前的位置: 首页 >  Java
  • 0浏览

    0关注

    674博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java实现自己的队列

沙漠一只雕得儿得儿 发布时间:2016-11-21 11:29:37 ,浏览量:0

package 栈与队列上;

import java.util.LinkedList;
/**
 * 定义节点
 * @author buder_cp
 *
 * @param 
 */
class ListNode {
	T val;
	ListNode next;

	public ListNode(T value, ListNode next) {
		super();
		this.val = value;
		this.next = next;
	}
}

/*
 * 建立自己的队列
 */
public class MiniQueue {

	private int size;

	public boolean isEmpty() {
		if (size == 0) {
			return true;
		} else {
			return false;
		}
	}

	public int size() {
		return size;
	}
	/**
	 * 初始化队列,两个指针
	 */
	private ListNode head;
	private ListNode last;

	public MiniQueue() {
		super();
		head = new ListNode(null, null); // 初始化两个指针
		last = head;
	}
	/**
	 * 从队尾添加元素
	 * @param t
	 */
	public void offer(T t) {
		ListNode node = new ListNode(t, null);
		last.next = node;
		last = node;
		size++;
	}
	/**
	 * 查看对头元素
	 * @return
	 */
	public T peek() {
		if (isEmpty()) {
			return null;
		} else {
			return head.next.val;
		}
	}
	/*
	 * 弹出队列投元素
	 */
	public T poll() {
		if (isEmpty()) {
			return null;
		} else {
			ListNode p = head.next;
			head.next = p.next;
			size--;
			if (size == 0) {
				last = head;
			}
			return p.val;
		}
	}

	public static void main(String[] args) {
		MiniQueue my_queue = new MiniQueue();
		System.out.println("队列初始化大小:" + my_queue.size);
		my_queue.offer(1);
		my_queue.offer(2);
		my_queue.offer(3);
		System.out.println("添加元素后大小:" + my_queue.size);
		while (!my_queue.isEmpty()) {
			System.out.print("弹出队列:" + my_queue.poll() + " ");
		}
	}
}

关注
打赏
1657159701
查看更多评论
立即登录/注册

微信扫码登录

0.0390s