首页 > 解决方案 > 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.

标签: javaalgorithmdata-structureslinked-listsingly-linked-list

解决方案


代码没有错误。

为了使列表表现得像 FIFO,节点将被添加到一端并从另一端删除。

因此,您将不得不实施删除操作。您可以维护对头节点和尾节点的单独引用。


推荐阅读