如何将字符串插入 java 中的链表
How to insert strings into a linked list in java
我正在编写一个程序,将String类型的数据添加到循环双向链表中,并在java中查看它们。
我想知道如何将字符串添加到链表以及如何获取输出。
我尝试的方式报错:“The constructor Node() is undefined”
如何解决这个问题。
这是我试过的代码:
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();
}
}
对于字符串更改:
class Node {
int data;
Node nextNode;
Node prevNode;
}
到
class Node {
String data;
Node nextNode;
Node prevNode;
}
或
class Node {
Object data;
Node nextNode;
Node prevNode;
}
(对象将允许任何数据类型)
我正在编写一个程序,将String类型的数据添加到循环双向链表中,并在java中查看它们。 我想知道如何将字符串添加到链表以及如何获取输出。
我尝试的方式报错:“The constructor Node() is undefined” 如何解决这个问题。
这是我试过的代码:
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();
}
}
对于字符串更改:
class Node {
int data;
Node nextNode;
Node prevNode;
}
到
class Node {
String data;
Node nextNode;
Node prevNode;
}
或
class Node {
Object data;
Node nextNode;
Node prevNode;
}
(对象将允许任何数据类型)