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

package queue;
/**
 * 使用单链表来实现队列
 * @author User
 *
 */
public class MyQueue1 {
	Node head;
	
	/**
	 * 入队
	 * @param data
	 */
	public void add(int data) {
		Node node = new Node(data);
		if(isEmpty()) {
			head = node;
		}else {
			Node temp = head;
			while(temp.next != null) {
				temp = temp.next;
			}
			// 此时temp为队列的最后一个元素
			temp.next = node;
		}
	}
	
	
	/**
	 * 出队
	 * @return
	 */
	public int remove() {
		if(isEmpty()) {
			throw new RuntimeException("队列是空的!");
		}
		int data = head.data;
		head = head.next;
		
		return data;
	}
	
	
	/**
	 * 打印
	 */
	public void print() {
		Node temp = head;
		while(temp != null) {
			System.out.print(temp.data + "  ");
			temp = temp.next;
		}
	}
	
	
	/**
	 * 获取队列长度
	 * @return
	 */
	public int length() {
		if(head == null) {
			return 0;
		}
		
		Node temp = head;
		// 计数器
		int count = 0;
		// 从头遍历到队尾
		while(temp != null) {
			temp = temp.next;
			count++;
		}
		
		return count;
	}
	
	/**
	 * 判空
	 * @return
	 */
	public boolean isEmpty() {
		return head == null;
	}
}


class Node{
	int data;
	Node next;
	
	public Node(int data) {
		this.data = data;
	}
}

 

你可能感兴趣的:(数据结构)