数据结构学习一队列:01 简单队列
程序员文章站
2024-03-18 11:34:40
...
package queue;
import java.util.ArrayList;
import java.util.List;
public class MyQueue {
//store elements
private List<Integer> data;
// a pointer to indicate the start position
private int p;
MyQueue(){
data = new ArrayList<Integer>();
p = 0;
}
/** insert an element into the queue,return true if the operation is successful*/
public boolean enqueue(int x) {
data.add(x);
return true;
}
/** delete an element into the queue, return true if the operation is successful*/
public boolean dequeue() {
if(isEmpty()) {
return false;
}
p++;
return true;
}
/** Check whether the queue is empty or not*/
public boolean isEmpty() {
return p>=data.size();
}
/** get the front item from the queue.*/
public int front() {
return data.get(p);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyQueue queue = new MyQueue();
queue.enqueue(1);
queue.enqueue(2);
if(queue.isEmpty()==false)
System.out.println(queue.front());
queue.dequeue();
if(queue.isEmpty()==false)
System.out.println(queue.front());
queue.dequeue();
if(queue.isEmpty()==false)
System.out.println(queue.front());
queue.dequeue();
}
}
数据结构思想:
- 先进先出,从队列头部出队,尾部入队
Java实现步骤
- 构造一个队列,以集合代替
- 设定一个指示在集合中位置的变量,相当于指针
- 对于队列的添加要判断队列是否满了
- 删除需要判断是否为空
上一篇: 趣味小游戏——扫雷(js开发)
下一篇: Java注解的简单了解