java - Java Simple Linked List
问题描述
I am taking a course in Data Structures at University and I am having troubles understanding why my Singly Linked List is not following FIFO algorithm.
Here is my Node/PSVM class:
public class Node {
protected int data;
protected Node next;
Node(int element){
this.data = element;
next = null;
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.addElement(300);
ll.addElement(600);
ll.addElement(900);
ll.addElement(1200);
ll.printList();
}
}
This is my Linked List Class:
public class LinkedList {
// create a reference of type node to point to head
Node head;
// keep track of the size of ll
int size = 0;
void printList() {
Node n = head;
for (int i = 0; i < llSize(); i++) {
System.out.print(n.data + " ");
n = n.next;
}
System.out.println("");
}
int llSize() {
return this.size;
}
boolean isEmpty() {
return size == 0;
}
void addElement(int element) {
if (isEmpty()) {
head = new Node(element);
} else {
Node nNode = new Node(element);
Node current = head;
while(current.next != null){
current = current.next;
}
current.next = nNode;
}
this.size++;
}
}
Sorry in advance if this is a basic question/problem. I have asked my professor and she sent me a YouTube link which really didn't help.
Thank you for your time.
解决方案
代码没有错误。
为了使列表表现得像 FIFO,节点将被添加到一端并从另一端删除。
因此,您将不得不实施删除操作。您可以维护对头节点和尾节点的单独引用。
推荐阅读
- laravel - 怎么给whereDate, whereMonth一个变量呢?
- docker - Snakemake + Docker 卷 - “缺少规则异常”
- python - 如何在python中为图像着色
- database - MongoDB 来管理模型用户和模型图像之类的关系或其他数据库替代品(例如 neo4j)来处理此问题
- c# - 如何在 .Net Core 中的 DateTime 上使用 XmlIgnore?错误消息说 DateTime 不可序列化
- php - 从数字到字符串 PHP 的日期
- jetty - Embedded Jetty 在应用程序退出后继续运行
- reactjs - 如何以编程方式在当前 url/路径上加载不同的路径/组件?
- javascript - 如何将多个结果返回到数组中?
- scala - Scala 解析器组合器