程序员代码面试指南读书笔记

编程入门 行业动态 更新时间:2024-10-24 04:38:17

<a href=https://www.elefans.com/category/jswz/34/1770040.html style=程序员代码面试指南读书笔记"/>

程序员代码面试指南读书笔记

问题描述:队列中的对象可能是狗,也可能是猫,popall pollcat polldog等
主要需要考虑的问题:记录入队列的时间

解题思路:
设计一个新类 ,添加一个count,用于记录add的顺序
package sharp1;import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;import javax.management.Query;class Pet{private String type;public Pet(String type){this.type = type;}public String getPetType(){return this.type;}	
}
class Dog extends Pet{public Dog(){super("Dog");}
}
class Cat extends Pet{public Cat(){super("Cat");}
}
//自定义一个class 需要考虑猫和狗哪个先进栈的
class PetEnterQueue{private Pet pet;private long count;public PetEnterQueue(Pet pet,long count){this.pet=pet;this.count = count;}public Pet getPet(){return this.pet;}public long getCount(){return this.count;}public String getEnterPetType(){return this.pet.getPetType();}
}
public class CatAndDagQueue {private Queue<PetEnterQueue> dogQ;private Queue<PetEnterQueue> catQ;private long count;public CatAndDagQueue(){this.dogQ = new LinkedList<PetEnterQueue>();this.catQ = new LinkedList<PetEnterQueue>();this.count = 0;}public void add(Pet pet){if(pet.getPetType().equals("Dog")){dogQ.add(new PetEnterQueue(pet, this.count++));}else if(pet.getPetType().equals("Cat")){catQ.add(new PetEnterQueue(pet, this.count++));			}else{throw new RuntimeException("err,not dag or cat");}}public Pet pollAll(){if(!this.dogQ.isEmpty() && !this.catQ.isEmpty()){if(this.dogQ.peek().getCount()<this.catQ.peek().getCount()){return this.dogQ.poll().getPet();}else{return this.catQ.poll().getPet();}}if(!this.dogQ.isEmpty()){return this.dogQ.poll().getPet();}else if(!this.catQ.isEmpty()){return this.catQ.poll().getPet();}else {throw new RuntimeException("queue is queue");}}public boolean isDogQueueEmpty(){return this.dogQ.isEmpty();}public boolean isCatQueueEmpty(){return this.catQ.isEmpty();}public Dog pollDog(){if(!this.isDogQueueEmpty()){return (Dog)this.dogQ.poll().getPet();}else {throw new RuntimeException("dog queue is empty");}		}public Cat pollCat(){if(!this.isCatQueueEmpty()){return (Cat)this.catQ.poll().getPet();}else {throw new RuntimeException("cat queue is empty");}}}

更多推荐

程序员代码面试指南读书笔记

本文发布于:2024-02-25 02:53:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1697545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序员   读书笔记   代码   指南

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!