如果任何歌曲包含对播放列表中上一首歌曲的引用,则播放列表被视为重复播放列表。否则,播放列表将以指向 null 的最后一首歌曲结束。
我需要实现一个函数 isRepeatingPlaylist,如果播放列表正在重复则返回 true,否则返回 false。
例如,当两首歌相互指向时,下面的代码打印“true”。
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
first.setNextSong(second);
second.setNextSong(first);
System.out.println(first.isRepeatingPlaylist());
再说一次,这不是家庭作业,我正在做编码挑战,因为当我阅读有关编程概念的理论时,我几乎可以理解,但是当面对编写程序时,我不知道从哪里开始,或者如何申请。
public class Song {
private String name;
private Song nextSong;
public Song(String name) {
this.name = name;
}
public void setNextSong(Song nextSong) {
this.nextSong = nextSong;
}
public boolean isRepeatingPlaylist() {
//throw new UnsupportedOperationException("Waiting to be implemented.");
List<String> list = new ArrayList<String>();
list.add(one);
list.add(two);
list.add(three);
list.add(four);
if list.contains()
return true;
else
return false;
}
public static void main(String[] args) {
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
Song third = new Song("a test");
Song fourth = new Song("survivor");
first.setNextSong(second);
second.setNextSong(first);
System.out.println(first.isRepeatingPlaylist();
}
}
最佳答案
您可以循环播放列表并将每首歌曲添加到集合中,条件是它还不在集合中。一旦到达列表末尾,您的列表就不是重复列表。如果您发现集合中已经存在的歌曲,则您有一个重复列表。
public boolean isRepeatingList(Song firstSong)
{
Set<Song> uniqueSongs=new HashSet<>();
uniqueSongs.add(firstSong);
Song current=firstSong;
while(current.getNextSong()!=null)
{
if(uniqueSongs.contains(current.getNextSong()))
return true;
// add the song to the set, and assign current to the next song
uniqueSongs.add(current=current.getNextSong());
}
// we reached the end of the list without finding any doubles, so:
return false;
}
关于java - 如果 array 或 arrayList 引用前一个元素,我如何实现一个返回 true 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55810756/