使用单向链表的方式来实现队列

 实体类

package queue;
/**
 * 用单链表的方式来实现队列
 * @author Administrator
 * @param <E>
 *
 */
public class MyQueue<E> {
	private Node<E> head = null;
	private Node<E> tail = null;
	
	/**
	 * 入队操作
	 * @param data
	 */
	public void goIn(E data) {
		Node<E> newNode = new Node<E>(data);
		if(head == null && tail == null) {
			head = tail = newNode;
		}
		tail.next = newNode;
		tail = newNode;
	}
	
	/**
	 * 出队操作
	 * @return
	 */
	public E goOut() {
		if(this.isEmpty()) {
			return null;
		}
		
		E data = head.data;
		head = head.next;
		return data;
	}

	/**
	 * 取得队列长度
	 * @return
	 */
	public int size() {
		Node<E> temp = head;
		int length = 0;
		while(temp != null) {
			length++;
			temp = temp.next;
		}
		
		return length;
	}
	
	/**
	 * 判空
	 * @return
	 */
	public boolean isEmpty() {
		
		return head == tail;
	}
}


/**
 * 结点类
 * @author Administrator
 *
 * @param <E>
 */
class Node<E>{
	// 数据域
	E data;
	// 指针域
	Node<E> next = null;
	// 构造器
	public Node(E data) {
		this.data = data;
	}
}

测试类

package queue;

public class Test {
	public static void main(String[] args) {
		MyQueue<Integer> queue = new MyQueue<>();
		queue.goIn(1);
		queue.goIn(2);
		queue.goIn(3);
		queue.goIn(4);

		System.out.println("队列长度为:" + queue.size());
		System.out.println("队列首元素为:" + queue.goOut());
		System.out.println("队列首元素为:" + queue.goOut());
		System.out.println("队列首元素为:" + queue.goOut());
	}

}

结果

猜你喜欢

转载自blog.csdn.net/qq_34741578/article/details/88693504
今日推荐