zoukankan      html  css  js  c++  java
  • 队列的链式存储方式的实现(Java语言描述)

    链队列的结构示意图:

    Java实现队列 - 队列内部使用链式存储结构

    先进先出。

    QueueInterface.java//操作方法接口

    package 队列的实现;
    
    public interface QueueInterface {
    	public void enQueue(Object t);
    	public Object delQueue();
    	public int size();
    	public boolean isEmpty();
    	public Object head();
    	public void clear();
    
    }
    


     

    Node.java//节点类

    package 队列的实现;
    
    public class Node<T> {
    	T data;
    	Node next;
    }
    

    Queue.java//队列的定义和接口实现

    package 队列的实现;
    
    public class Queue<T> implements QueueInterface{
        Node<T> front,rear;//对头指针,队尾指针
        //构造一个空的链队列
        public Queue(){
        	front = new Node<T>();
        	rear = new Node<T>();
        	rear = front;
        }
    	//实现接口里的操作
        public boolean isEmpty(){
    		if(front == rear)
    			return true;
    		else
    			return false;
    	}
        public int size(){
        	int i = 0;
        	Node<T> p = front.next;
        	while(p != null){
        		p = p.next;
        		i++;
        	}
        	return i;
        }
        public Object head(){
        	if(this.isEmpty() == false)
        	return front.next.data;
        	System.out.println("队列为空,不存在队头元素!");
        	return 0;
        }
    	public void enQueue(Object obj){
    		Node<T> p = new Node<T>();
    		p.data = (T)obj;
    		rear.next = p;
    		p.next = null;
    		rear = p;
    	}
    	public Object delQueue(){
    		T t;
    		Node<T> p = new Node<T>();
    		if(this.isEmpty() == true){
    			System.out.println("队列为空,不能进行删除操作!");
    			return 0;
    		}
    		else{
    			p = front.next;
    			front.next = p.next;
    			if(p.next == null)//出队后队列为空
    				rear = front;
    			t = p.data;
    			p = null;
    			return t;
    		}
    	}
    	public void clear(){
    		front = rear;
    	}
    
    }
    

    TestQueue.java//测试类

    package 队列的实现;
    
    public class TestQueue {
    
    	public static void main(String[] args) {
    		Queue<Integer> queue = new Queue<Integer>();
    		for(int i=1; i<=10; i++){
    			queue.enQueue(i);
    		}
    		System.out.println(queue.size());
    		System.out.println(queue.isEmpty());
    		for(int i=1; i<=10; i++){
    			System.out.print(queue.delQueue() + " ");
    		}
    		System.out.println();
    		System.out.println(queue.isEmpty());
    		for(int i=1; i<=10; i++){
    			queue.enQueue(i);
    		}
    		System.out.println(queue.isEmpty());
    		queue.clear();
    		System.out.println(queue.isEmpty());
    
    	}
    
    }
    


    实现结果:

    10
    false
    1 2 3 4 5 6 7 8 9 10
    true
    false
    true


     

  • 相关阅读:
    Windows 操作系统引导过程 BIOS & EFI
    Mac 系统引导过程概述 & BootCamp 的秘密
    Windows 10 安装 Ubuntu 子系统
    nrm 安装及报错处理
    司马懿人物关系
    大江大河
    曹操人物关系
    必要条件探路(导数)
    该题七种想法(一题一课之外接球)
    欧拉-查柏(Euler-Chapple)公式及其推广
  • 原文地址:https://www.cnblogs.com/wxisme/p/4363787.html
Copyright © 2011-2022 走看看