I have a LinkedList that I have created when used creates a Band, Song, and Duration of the song list.
Example output:
Band: Led Zepplen | Song: Stairway to Heaven | Duration: 8.02 minutes
Band: AC/DC | Song: Back in Black | Duration: 4.14 minutes
Band: The Rolling Stones | Song: Paint it Black | Duration: 3.46 minutes
What I can't figure out is how to implement a method where I can insert a node in any given position. So far my code looks like this:
public class Song {
private String band;
private String name;
private double duration;
Song next;
public Song(String band, String name, double duration) {
this.band = band;
this.name = name;
this.duration = duration;
}
public String getBand() {
return band;
}
public void setBand(String band) {
this.band = band;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getDuration() {
return duration;
}
public void setDuration(double duration) {
this.duration = duration;
}
public Song getNext() {
return next;
}
public void setNext(Song next) {
this.next = next;
}
public Song getLastNode() {
Song currentNode = this;
while(currentNode.next != null) {
currentNode = currentNode.next;
};
return currentNode;
}
public void append(Song newSong) {
Song tmpNode = this.getLastNode();
tmpNode.next = newSong;
}
public void printAllSongs() {
// print all songs from j
Song currentNode = this;
do {
System.out.println("Band: " + currentNode.getBand() + " | " +
" Song: " + currentNode.getName() + " | " +
" Duration: " + currentNode.getDuration() + " minutes");
currentNode = currentNode.next;
} while( currentNode != null );
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Song mySong = new Song("Led Zepplen", "Stairway to Heaven", 8.02);
mySong.append(new Song ("AC/DC", "Back in Black", 4.14 ));
mySong.append(new Song("The Rolling Stones", "Paint it Black", 3.46));
mySong.printAllSongs();
}
}
What is one way I could achieve coding a method that inserts a node at any given position?
Songshould not have anext. When you have a linked-list, each element has anextand should have avalue-- in your case the value is a Song object; so it is the listNodeobject that should have a value and a next (otherwise any sort of object you might ever want to put in a list must have a "next")