1. 程式人生 > >java代碼實現順序隊列

java代碼實現順序隊列

rgs util vat integer gen 查看 int [] tab

java實現順序隊列

package xianxinTable;

import java.util.ArrayList;
import java.util.Iterator;

import com.sun.java_cup.internal.internal_error;

public class queue_self<E> implements Iterator<E> {
	// 定義一個簡單的叠代器
	
	public iterator itertor(){
		
		return new iterator();
		
	}
	
	
	class iterator implements Iterator<E> {
		// 要叠代的長度
		private int size;
		// 當前叠代到達位置
		private int nowsize;

		iterator() {
			size = queue_self.this.length;
			nowsize = 1;

		}

		public boolean hasNext() {
			if (nowsize != size+1) {
				// TODO Auto-generated method stub
				return true;
			} else {
				return false;
			}

		}

		public E next() {
			// TODO Auto-generated method stub
			int page=nowsize;
			nowsize++;
			return queue_self.this.datalist.get(page-1);
		}

		public void remove() {
			// TODO Auto-generated method stub

		}

	}

	// 定義數組長度
	private int length;
	// 存放數組內容
	private ArrayList<E> datalist;
	// 隊列頭
	private int head;
	// 隊列尾
	private int rear;

	// 隊列初始化
	public queue_self() {
		datalist = new ArrayList<E>();
		this.length = 0;
		head = 0;
		rear = 0;

	}

	// 入隊
	public boolean offer(E data) {
		if (true) {
			this.datalist.add(data);
			
			length++;
			return true;
		} else {

			return false;
		}

	}

	// 出隊
	public E poll() {
		E e = null;
		if (length == 0) {
			return e;

		} else {
			e = this.datalist.get(head);
			this.datalist.remove(head);
			length--;
			return e;

		}

	}

	// 查看隊首元素
	public E peek() {
		E e = null;
		if (length == 0) {
			return e;

		} else {
			e = this.datalist.get(head);

			return e;

		}

	}

	// 返回隊列長度

	public int length() {

		return this.length;

	}

	public static void main(String[] args) {

		queue_self<Integer> q = new queue_self<Integer>();
		q.offer(2);
		q.offer(44);
        q.offer(66);
        q.poll();
		Iterator<Integer> it=q.itertor();
		while(it.hasNext()){
			
			System.out.println(it.next());
			
		}
		
	}

	public boolean hasNext() {
		// TODO Auto-generated method stub
		return false;
	}

	public E next() {
		// TODO Auto-generated method stub
		return null;
	}

	public void remove() {
		// TODO Auto-generated method stub

	}

}

  輸出:

44
66

  

java代碼實現順序隊列