要求:
- 1 用实现循环队列
- 2 参考PPT用循环队列打印杨辉三角
- 3 用JDB或IDEA单步跟踪排队情况,画出队列变化图,包含自己的学号信息
- 4 把代码推送到代码托管平台
- 5 把完成过程写一篇博客:重点是单步跟踪过程和遇到的问题及解决过程
- 6 提交博客链接
分析过程:
- 杨辉三角的构造,其两腰上的数都唯一,其余每个数都为其上方左右两数之和
- 为计算方便首尾加0
- 具体思路和老师的PPT大概一致(附图)
代码一:CircularArrayQueue
public class CircularArrayQueue<T> implements Queue<T>
{
private final int DEFAULT_CAPACITY = 10000;
private int front, rear, size;
private T[] queue;
//-----------------------------------------------------------------
// Creates an empty queue using the default capacity.
//-----------------------------------------------------------------
public CircularArrayQueue()
{
front = rear = size = 0;
queue = (T[]) (new Object[DEFAULT_CAPACITY]);
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of this queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enqueue (T element)
{
if (size == queue.length)
expandCapacity();
queue[rear] = element;
rear = (rear+1) % queue.length;
size++;
}
public void expandCapacity()
{
T[] larger = (T[])(new Object[queue.length*2]);
for (int index = 0; index < size; index++)
larger[index] = queue[(front+index) % queue.length];
front = 0;
rear = size;
queue = larger;
}
@Override
public T dequeue()
{
if (size == 0)
throw new EmptyCollectionException("queue");
T d = queue[front];
queue[front] = null;
front = (front+1)%queue.length;
size--;
return d;
}
@Override
public T first() {
return queue[front];
}
@Override
public boolean isEmpty() {
boolean course = false;
if(size ==0){
course = true;
}
return course;
}
@Override
public int size() {
return size;
}
@Override
public String toString(){
String result = "";
int scan = 0;
while(scan < size)
{
if(queue[scan]!=null)
{
result += queue[scan].toString()+"\n";
}
scan++;
}
return result;
}
}
代码二:杨辉三角
import java.util.Scanner;
public class YangHuiSanJiao {
public static void main(String[] args) {
System.out.println("输入行数:");
Scanner sca = new Scanner(System.in);
CircularArrayQueue qu = new CircularArrayQueue();
qu.enqueue(0);
qu.enqueue(1);
int b = sca.nextInt();
int z=0,j= 0,d;
System.out.println(1);
for (int a = 1;a<= b - 1; a++){
qu.enqueue(0);
for (int ai =1;ai< qu.size();ai++){
z= (int) qu.first();
qu.dequeue();
j = (int) qu.first();
d = z+j;
qu.enqueue(d);
System.out.print(d + " ");
}
System.out.println();
}
}
}
单步跟踪结果截图: