标签:
package com.wxisme.linkqueue; import java.util.Scanner; /** * 链队列的实现 * @time 2015/8/16 0:16 * @author wxisme * */ public class LinkQueue<T> { private class Node { private T data; private Node next; public Node() {} public Node(T data) { this.data = data; } } private Node front; /*队头*/ private Node rear; /*队尾*/ private int size; /*长度*/ public LinkQueue() { front = null; rear = null; } public LinkQueue(T data) { front = new Node(data); rear = front; size ++; } //队列的长度 public int size() { return size; } //从队尾入队 public void add(T data) { if(front == null) { front = new Node(data); rear = front; size ++; } else { Node node = new Node(data); rear.next = node; rear = node; size ++; } } //从队头出队 public T remove() { T t = null; if(front != null) { t = front.data; Node node = front; front = front.next; node.next = null;//释放对头元素的引用,等待垃圾回收。 size --; } else { try { throw new Exception("队列已经为空,不能移除元素!"); } catch (Exception e) { e.printStackTrace(); } } return t; } //读取对头元素 public T peek() { if(front == null) { try { throw new Exception("队列为空,不能读取对头元素!"); } catch (Exception e) { e.printStackTrace(); } return null; } else { return front.data; } } //清空队列 public void clear() { front = rear = null; size = 0; } //判断是否为空 public boolean isEmpty() { return size==0; } public String toString() { if(isEmpty()) { return "[]"; } else { StringBuilder str = new StringBuilder("[" + front.data); for(Node node=front.next; node!=null; node=node.next) { str.append(","+node.data); } str.append("]"); return str.toString(); } } /** * 测试代码 * @param args */ public static void main(String[] args) { LinkQueue<Character> queue = new LinkQueue<Character>(); Scanner scan = new Scanner(System.in); for(int i=0; i<5; i++) { queue.add((char)(‘a‘+i)); } System.out.println(queue); queue.remove(); System.out.println(queue); System.out.println("队列是否为空:" + queue.isEmpty()); System.out.println("队列的长度:" + queue.size()); System.out.println("队头元素为:" + queue.peek()); System.out.println("清空队列"); queue.clear(); System.out.println("队列是否为空:" + queue.isEmpty()); } }
测试结果:
[a,b,c,d,e]
[b,c,d,e]
队列是否为空:false
队列的长度:4
队头元素为:b
清空队列
队列是否为空:true
标签:
原文地址:http://www.cnblogs.com/wxisme/p/4733442.html