自己实现一个队列(Java)

思路:

1、链表实现,不用考虑扩容问题

2、节点维护next指针,每次删除元素,删除头结点,插入元素队尾插入

代码:

package com.datastructure.stackqueue;

/**
 * 实现一个栈,自定义栈,用链表实现,方便扩容 
 */
public class DefineQueue<T> {

	private Node<T> root;
	
	private Node<T> tail;
	
	static class Node<T> {
		T value;
		Node<T> next;
		Node (T value) {
			this.value = value;
		}
		
        @Override
        public String toString() {
            if (this.next == null) {
                return String.valueOf(this.value);
            }
            return this.value + "->" + this.next.toString();
        }
	} 
	
	/**
	 * 有前驱指针的节点
	 * 
	 * root -> tail
	 *  
	 */
	public T offer(T t) {
		if (root == null) {
			root = new Node<T>(t);
			tail = root;
			return t;
		}
		
		Node<T> node = new Node<T>(t);
		tail.next = node;
		
		// tail 右移
		tail = node;
		
		return t;
	}
	
	public T poll() {
		if (null == root) {
			throw new RuntimeException("stack is empty");
		}
		
		if (root == tail) {
			Node<T> node = root;
			root = null;
			tail = null;
			return node.value;
		}
		
		Node<T> retNode = root;
		root = root.next;
		
		return retNode.value;
	}
	
	@Override
	public String toString() {
		return this.root.toString();
	}
	
	public static void main(String[] args) {
		DefineQueue<Integer> s = new DefineQueue<>();
		s.offer(1);
		s.offer(2);
		s.offer(3);
		s.poll();
		s.offer(4);
		s.offer(5);
		s.poll();
		System.out.println(s);
	}

}

猜你喜欢

转载自blog.csdn.net/zangdaiyang1991/article/details/88628826