1

I am writing a program to add String type data to a circular doubly linked list and to view them in java. I want to know that how to add Strings to the linked list and how to get the output.

The way I tried gives an error: " The constructor Node() is undefined " How to fix this.

here is the code I tried:

class Node {
    int data;
    Node nextNode;
    Node prevNode;
}

class CircularDoublyLL {
    Node head = null;
    Node tail = null;

    public void insertLast(String songName) {
        Node newNode = new Node();
        newNode.data = songName;

        if (head == null) {
            head = tail = newNode;
            head.nextNode = head;
            head.prevNode = head;
        } else {
            tail.nextNode = newNode;
            newNode.prevNode = tail;
            newNode.nextNode = head;
            head.prevNode = newNode;
            tail = newNode;
        }
    }

    public void displayPlayist() {
        Node currentNode = head;
        if (head == null) {
            System.out.println("Playlist is empty!");
        } else {
            int songNo = 1;
            while (currentNode != tail) {
                System.out.println("Song " + songNo + ": " + currentNode.data);
                currentNode = currentNode.nextNode;
                songNo++;
            }
            System.out.println("Song " + songNo + ": " + currentNode.data);
        }
    }
}

public class MusicPlayer {
    public static void main(String[] args) {
        CircularDoublyLL playlist = new CircularDoublyLL();

        playlist.insertLast("Song Name 1");
        playlist.insertLast("Song Name 2");
        playlist.insertLast("Song Name 3");
        playlist.insertLast("Song Name 4");
        playlist.displayPlayist();
    }
}
  • Does this answer your question? [Java Error: The constructor is undefined](https://stackoverflow.com/questions/18159104/java-error-the-constructor-is-undefined) – lkatiforis Dec 31 '21 at 07:41
  • I have checked that also but I want to know how to insert strings to LinkedList and view them – Tharisha Perera Dec 31 '21 at 08:04

1 Answers1

1

For Strings change:

class Node {
    int data;
    Node nextNode;
    Node prevNode;
}

To

class Node {
    String data;
    Node nextNode;
    Node prevNode;
}

or

class Node {
    Object data;
    Node nextNode;
    Node prevNode;
}

(Object will allow any data type)

AminM
  • 822
  • 4
  • 11
  • In this situation, it would probably be better not to use a pre-Java version 5 solution but rather give a more robust and modern (post-2004) version that makes use of generics. – Hovercraft Full Of Eels Dec 31 '21 at 12:13
  • @HovercraftFullOfEels yes.. you could use a generics solution as well. I was just trying to keep it simple. – AminM Jan 01 '22 at 19:35