一直致力于实现链表队列和堆栈类的赋值。我已经测试了这两种方法,它们似乎都在工作,但我担心实现的某些部分可以做得比我目前设置的更好,我不想因为低效的代码而被扣分。
下面是我设置的类:
节点
public class Node {
Node next;
Car car;
/**
* A node object, used for the creation of LinkedLists.
* @param car
*/
public Node(Car car)
{
next = null;
this.car = car;
}
}
堆栈
public class LStack {
Node head = null;
/**
* Adds a car object to the list
* @param car = the car object to be added
*/
public void push(Car car)
{
Node oldHead = head;
head = new Node(car);
head.next = oldHead;
}
/**
* Removes the top car from the list
* @return the car at the top of the list
*/
public Car pop()
{
Car headCar = head.car;
head = head.next;
return headCar;
}
/**
* Checks if the list is empty
* @return whether or not the list is empty
*/
public boolean isEmpty()
{
return (head == null);
}
/**
*
* @return the size of the list
*/
public int size()
{
Node nextNode = head;
int count = 0;
while (nextNode != null)
{
count++;
nextNode = nextNode.next;
}
return count;
}
/**
* Displays the list of car license plate information
*/
public void display()
{
Node nextNode = head;
while (nextNode != null)
{
System.out.print(nextNode.car.getLicense() + "|");
nextNode = nextNode.next;
}
System.out.println();
}
/**
*
*/
public void reverseStack()
{
// not implemented yet
}
}
队列public class LQueue {
Node head = null;
/**
* Adds a car object to the list
*
* @param car
* = the car object to be added
*/
public void insert(Car car) {
Node current = head;
if (current != null) {
while (current.next != null) {
current = current.next;
}
current.next = new Node(car);
}
else
{
head = new Node(car);
}
}
/**
* Removes the top car from the list
*
* @return the car at the top of the list
*/
public Car remove() {
Car headCar = head.car;
head = head.next;
return headCar;
}
/**
* Checks if the list is empty
*
* @return whether or not the list is empty
*/
public boolean isEmpty() {
return (head == null);
}
/**
*
* @return the size of the list
*/
public int size() {
Node nextNode = head;
int count = 0;
while (nextNode != null) {
count++;
nextNode = nextNode.next;
}
return count;
}
/**
* Displays the list of car license plate information
*/
public void display() {
Node nextNode = head;
while (nextNode != null) {
System.out.print(nextNode.car.getLicense() + "|");
nextNode = nextNode.next;
}
System.out.println();
}
/**
*
*/
public void reverseQueue() {
}
}
和Car类其实并不重要,它只是将车牌信息存储在一个字符串中。
我最担心的是我用While循环设置的那些,我不确定是否有更有效的内存实现方式。有没有更标准化的方法来设置这些,我可能错过了?
我要改变的一件事是,我将使LQueue
保持对队列头部和尾部的引用。这样,您就可以在恒定时间内获得insert()
,而不必遍历所有现有元素。
此外,如果您愿意,两个size()
方法都可以在恒定时间内运行:跟踪成员变量的当前大小,在insert()
上递增,在remove()
上递减。
我能想到的只有两件事:
-
用添加时递增、移除时递减的int值跟踪列表中元素的数量。这将使size()方法成为即时的。你所要做的就是返回int值
-
对于队列,使用Node引用跟踪尾部,就像跟踪头部一样。这样就不必遍历列表来找到列表的末尾。尾部总是最后添加的节点。这将允许你不必在每次想要添加内容时遍历列表;相反,你可以把它添加到尾巴的末端。