20172302 《Java软件结构与数据结构》第三周学习总结


2018年学习总结博客总目录:[第一周](https://www.cnblogs.com/hzy0628/p/9606767.html) [第二周](https://www.cnblogs.com/hzy0628/p/9655903.html) [第三周](https://www.cnblogs.com/hzy0628/p/9700082.html)

教材学习内容总结

第五章 队列

1.队列是一种线性集合,其元素从一端加入,从另一端删除;队列元素是按先进先出(FIFO(First in First out))方式进行处理的。

2.队列ADT所定义的一些基本操作,见下表

操作 描述
enqueue 向列表末端添加一个元素
dequeue 从队列前端删除一个元素
first 考察队列前端的那个元素
isEmpty 判定队列是否为空
size 判定队列中的元素数目
toString 返回队列的字符串表示

3.Java API中的队列
java.util包中有接口 Queue,它提供了以下一些方法:

4.队列的两个应用:代码密钥,售票口模拟。

5.队列ADT
我们定义一个泛型QueueADT接口,表示队列的操作,把操作的一般目标与各种实现方式分开。下面是其UML描述:

下面为其代码:

public interface QueueADT<T>
{
    public void enqueue(T elem);
    public T dequeue();
    public T first();

    public boolean isEmpty();

    public int size();
    public String toString();
}

6.用链表实现队列

  • 队列链表表头:
import jsjf.*;

public class LinkedQueue<T> implements QueueADT<T>
{
    private int count;
    private LinearNode<T> head,tail;

    public LinkedQueue()
    {
        count = 0 ;
        head = tail = null;
    }
  • enqueue操作
    要求将新元素放置与链表末端,即将当前末元素的next引用设置指向新元素,并重新将tail引用指向这个新添加的末元素,代码实现如下:
public void enqueue(T element) {
        
            LinearNode<T> node = new LinearNode<T>(element);

            if (isEmpty())
                head = node;
            else
                tail.setNext(node);

            tail = node;
            count++;
        

    }
  • dequeue操作
    首先确保队列中存在至少一个可返回元素,返回该链表的首元素,然后更新head引用,代码实现如下:
public T dequeue() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("queue");

        T result = head.getElement();
        head = head.getNext();
        count--;

        if (isEmpty())
            tail = null;

        return result;
    }

7.用数组实现队列

这里我们首先考虑一个一般数组,由于队列操作会修改集合的两端,因此要将一端固定于索引为0处移动元素,这样便有两种可能:(1)首元素永远固定在数组索引为0处,这时添加元素时复杂度为O(1),而删除元素时,复杂度将会变为O(n);(2)队列的末元素始终固定在数组索引为0处,这时删除一个元素时复杂度为O(1),而添加一个新元素时则会使复杂度变为O(n)。无论以上哪种情况,都不是最好的解决办法。这时,我们可以去采用环形数组(circular array)来实现队列,即一种环形的数组结构。

  • 队列的环形数组表头
public class CircularArrayQueue<T> implements QueueADT<T>
{
    private final static int DEFAULT_CAPACITY = 100;
    private int front, rear, count;
    private T[] queue; 
  
    /**
     * Creates an empty queue using the specified capacity.
     * @param initialCapacity the initial size of the circular array queue
     */
    public CircularArrayQueue (int initialCapacity)
    {
        front = rear = count = 0;
        queue = (T[]) (new Object[initialCapacity]);
    }
  
    /**
     * Creates an empty queue using the default capacity.
     */
    public CircularArrayQueue()
    {
        this(DEFAULT_CAPACITY);
    }

rear的值代表数组的下一个可用单元。

  • enqueue操作
    一个元素入列后,rear的值递增,但当enqueue操作填充了数组的最后一个单元时,rear的值需要重新设定为0。故rear的值需要这样进行更新:rear = (rear+1) % queue.length;,同时,当数组中的所有单元已经填充,这时就需要扩容这一操作,不然新元素会覆盖掉之前的首元素。
    具体代码实现:
public void enqueue(T element)
    {
        if (size() == queue.length) 
            expandCapacity();
    
        queue[rear] = element;
        rear = (rear+1) % queue.length;
    
        count++;
    }
	
	/**
     * Creates a new array to store the contents of this queue with
     * twice the capacity of the old one.
     */
    private void expandCapacity()
    {
        T[] larger = (T[]) (new Object[queue.length *2]);
    
        for (int scan = 0; scan < count; scan++)
        {
            larger[scan] = queue[front];
            front = (front + 1) % queue.length;
        }
    
        front = 0;
        rear = count;
        queue = larger;
    }
  • dequeue操作
    一个元素出列后,front值需要递减,进行足够的dequeue操作后,front值将达到数组的最后一个索引处。
    具体代码实现:
public T dequeue() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("queue");
    
        T result = queue[front];
        queue[front] = null;
        front = (front+1) % queue.length;
    
        count--;
    
        return result;
    }

8.双端队列
双端队列(deque)是队列的拓展,它允许从队列的两端添加、删除和查看元素。

教材学习中的问题和解决过程

  • 问题1:关于书上售票口模拟的代码的理解,即对TicketCounter类的不太明白。
Customer customer;
        Queue<Customer> customerQueue = new LinkedList<Customer>();

        int[] cashierTime = new int[MAX_CASHIERS];
        //收银员的时间标记
        int totalTime, averageTime, departs,start;

        /** process the simulation for various number of cashiers */
        for (int cashiers = 0; cashiers < MAX_CASHIERS; cashiers++) 
        {
            /** set each cashiers time to zero initially */
            for (int count = 0; count < cashiers; count++)
                cashierTime[count] = 0;

            /** load customer queue */
            for (int count = 1; count <= NUM_CUSTOMERS; count++)
                customerQueue.offer(new Customer(count * 15));

            totalTime = 0;//使用的总体时间

            /** process all customers in the queue */
            while (!(customerQueue.isEmpty()))
            {
                for (int count = 0; count <= cashiers; count++) 
                {
                    if (!(customerQueue.isEmpty()))
                    {
                        customer = customerQueue.poll();
                        if (customer.getArrivalTime() > cashierTime[count])
                            start = customer.getArrivalTime() ;
                        else
                            start = cashierTime[count];

                        // 离开时间的设置
                        departs = start + PROCESS;
                        customer.setDepartureTime(departs);
                        cashierTime[count] = departs;
                        //每个顾客使用的最总时间
                        totalTime += customer.totalTime();

                    }
                }
            }
            
            averageTime = totalTime / NUM_CUSTOMERS;
            System.out.println("Number of cashiers: " + (cashiers + 1));
            System.out.println("Average time: " + averageTime + "\n");
        }
  • 问题1解决方案:这个类看了有将近20分钟才能理解其中各个循环以及各行代码其中含义。
    我们首先确定好每个循环,for (int cashiers = 0; cashiers < MAX_CASHIERS; cashiers++) {},这是最外层的一个循环,这个循环要完成的是模拟售票口数量,从1开始到10结束,那么我们现在可以先把它固定下来,假定现在cashiers=4,然后继续;
for (int count = 0; count < cashiers; count++)
                cashierTime[count] = 0;

            /** load customer queue */
            for (int count = 1; count <= NUM_CUSTOMERS; count++)
                customerQueue.offer(new Customer(count * 15));

            totalTime = 0;//使用的总体时间

这几行代码是将每个cashier time初始化为0,同时再导入每位顾客来的时间,总体时间设为0,然后继续;
到了这里while (!(customerQueue.isEmpty())){},又是一个较大的循环,当队列不为空时,售票口就需要处理,继续;
再内层的 for (int count = 0; count <= cashiers; count++) {}这个循环模拟的是各个售票口进行处理,我们刚才固定cashiers为4,那么这个循环就会进行5次,此时各个售票口进行处理;
然后,

customer = customerQueue.poll();
 if (customer.getArrivalTime() > cashierTime[count])
                            start = customer.getArrivalTime() ;
                        else
                            start = cashierTime[count];
                       departs = start + PROCESS;
                        customer.setDepartureTime(departs);
                        cashierTime[count] = departs;
                        //每个顾客使用的最总时间
                        totalTime += customer.totalTime();

这里是我理解起来最费力气的一个地方,首先是一位顾客出队进行办理,我们要计算他在这里的等待时间,比如说第第150秒来的顾客,他恰好走到了第3个售票口,那么如果他来的时间是在前一位顾客已经离开之后,那么他将不用等待,之间记开始start为他来的时间,然后加上他处理的时间,就是他离开的时间;那么,如果他来的时候,前面还有顾客没有处理完,那么这时就有等待时间了,等待的时间就是这个售票口处所记的counterTime,再加上他的处理时间,就是他离开的时间。后面的就比较容易理解了,不再叙述。
这样就完成了整个的售票口的一个模拟流程,得到了书上的结果。

代码调试中的问题和解决过程

  • 问题:关于书上习题PP5.7,其中要求的双端队列可以用单链表实现,不会用双向链表进行实现。

  • 问题解决方案:暂时还不会。双向链表不知道previous这个节点该怎么去使用,还不会解决。学会后补这里解决方案。

————————————————-————————————————————-

  • 补上面问题解决办法:
    问题主要在于双端链表如何解决,如何用双端列表去实现队列?
class Link
{
	public long dData;
	public Link next;
	public Link(long dData)
	{
		this.dData = dData;
	}
	public void displayLink()
	{
		System.out.print("{" + this.dData + "}");
	}
}

首先是创建一个节点类,然后建立一个链表;

class FirstLastList
{
	Link first;
	Link last;
 
	public FirstLastList()
	{
		this.first = null;  //when create an object of LinkList,make sure it is empty!
		this.last = null;
	}
 
	public boolean isEmpty()
	{
		return first == null;
	}
 
	public void insertLast(long key)	//this method will be used when I create insert() method 
	{									//in Queue(not the class Queue,I just mean a Queue)
		Link newLink = new Link(key);
		if(this.isEmpty())				//if list is empty
		{
			first = newLink;			//draw a picture can help me understand it !
			last = newLink;
			newLink.next = null;
		}
		else
		{
			last.next = newLink;
			last = newLink;
			newLink.next = null;
		}
	}
 
	public long deleteFirst()		//this method will be used when I create remove() method in Queue(not the class Queue,I just mean a Queue)
	{
		Link current = null;
		if(this.isEmpty())
		{
			System.out.println("Your stack is empty");
			return -1;
		}
		else if(first==last)
			{
				current = first;
			    first = null;
			    last = null;
			    return current.dData;
			}
			else
			{
				current = first;
				first = first.next;
				return current.dData;
			}
			
	}
 
	public void displayList()
	{
		Link current = first;
		System.out.print("Queue (front-->rear): ");
		if(this.isEmpty())
		{
			System.out.println("Your list is empty, nothing to show!");
		}
		else
		{
			while(current!=null)
			{
				current.displayLink();
				current = current.next;
			}
			System.out.println("");
		}
	}
}
 
class LinkQueue
{
	FirstLastList list = new FirstLastList();	//two-ended list
	public void insert(long key)
	{
		list.insertLast(key);
	}
	public long remove()
	{
		return list.deleteFirst();
	}
	public void showQueue()
	{
		list.displayList();
	}
}
 
class LinkQueueApp
{
	public static void main(String[] args)
	{
		LinkQueue theQueue = new LinkQueue();
		theQueue.insert(12);	//insert four elements
		theQueue.insert(13);
		theQueue.insert(14);
		theQueue.insert(15);
 
		theQueue.showQueue();	//look at what is in the queue
 
		theQueue.remove();		//remove two elements ,from right side
		theQueue.remove();
		theQueue.showQueue();	//look at what is in the queue now!
	}
}

双端链表实际上是比单链表多了一个指向最后一个节点的引用,其他的实现与单链表相同。

代码托管

上周代码行数为8255行,现在为8867行,本周共612行

上周考试错题总结

  • 1.By using the interface name as a return type, the interface doesn’t commit the method to the use of any particular class that implements a stack.(正确)

  • 解析:通过使用接口名作为return类型,接口不会将该方法提交给任何实现堆栈的特定类。

  • 2.The implementation of the collection operations should affect the way users interact with the collection.(错误)

  • 解析:集合的操作方式不能够影响用户与集合元素的交互方式。

  • 3.Inherited variables and methods can be used in the derived class as if they had been declared locally.(正确)

  • 解析:继承的变量和方法可以在派生类中使用,就如它们是本地声明的一样。

结对及互评

  • 本周结对学习情况
    • 20172308

    • 博客中值得学习的或问题: 博客中代码问题解决过程记录较详细,可适当添加教材内容总结。

    • 结对学习内容:学习第5章内容——队列

其他(感悟、思考等)

感悟

  • 本周学习时间不长,中秋三天假期没有看到布置的作业,也没有提前进行预习,作业完成的比较匆忙,希望国庆假期结束后能投入多些时间进行学习,同时复习前面所学。

补充作业

  • 我认为,现在的专业知识还差很多,同时目前所了解的大部分知识应该是属于基础知识,涉及到的专业很少,理解程度也还不够;技能方面欠缺的主要是熟练度,如果不可以参考任何资料书籍,就让我开始编写一个程序,我觉得有很大的可能是无法完成的,这也正是熟练度还不够的一个体现;能力方面我觉得差一些的是一个整体的把握,拿到一个复杂编程题目,整体的方向怎么做,从哪下手更容易,UML图如何去画,这里仍存在很多不足。
  • Skill 技能
技能 课前评估 课后希望值
对编程的整体理解 2 6
程序理解 4 8
单元测试、代码覆盖率 1 6
效能分析和改进 3 7
需求分析 0 5
计划任务 2 7

学习进度条

代码行数(新增/累积) 博客量(新增/累积) 学习时间(新增/累积) 重要成长
目标 5000行 30篇 400小时
第一周 0/0 1/1 15/15
第二周 572/572 1/2 16/31
第三周 612/1184 1/3 13/44

参考资料

posted @ 2018-09-26 19:17  ◕‿◕  阅读(296)  评论(0编辑  收藏  举报
© 2018 GitHub, Inc.