我如何查找其重复播放列表?

时间:2019-07-26 09:31:37

标签: c# class

我需要确定播放列表是否在重复。从我下面的代码请帮助建议解决方案。 如果任何歌曲包含对播放列表中上一首歌曲的引用,则该播放列表被视为重复播放列表。否则,播放列表将以最后一首指向null的歌曲结尾。

using System;

public class Song
{
    private string name;
    public Song NextSong { get; set; }

    public Song(string name)
    {
        this.name = name;
    }

    public bool IsRepeatingPlaylist()
    {
        if(this.name == NextSong.name)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static void Main(string[] args)
    {
        Song first = new Song("Hello");
        Song second = new Song("Eye of the tiger");

        first.NextSong = second;
        second.NextSong = first;

        Console.WriteLine(first.IsRepeatingPlaylist());
    }
}

2 个答案:

答案 0 :(得分:1)

public boolean isRepeatingPlaylist() {
    Song next = this.NextSong;
    while (next != null) {
        if (next.name.equalsIgnoreCase(name)) {
            return true;
        }
        next = next.NextSong;
    }
    return false;
}

答案 1 :(得分:0)

这似乎等同于检查链表中的循环,因此我们可以简单地使用Floyd's "Tortoise and Hare" cycle detection algorithm

public bool IsRepeatingPlaylist()
{
    Song slow = this;
    Song fast = this.NextSong;

    while (slow != null && fast != null)
    {
        if (ReferenceEquals(slow, fast))
            return true;

        slow = slow.NextSong;
        fast = fast.NextSong?.NextSong;
    }

    return false;
}

下面是一些测试播放列表的代码,其中播放列表的末尾会循环回到播放列表中途的歌曲:

static void Main()
{
    Song start = new Song("1");
    Song curr  = start;

    Song halfway = null;

    for (int i = 2; i < 100; ++i)
    {
        curr.NextSong = new Song(i.ToString());
        curr = curr.NextSong;

        if (i == 50)
            halfway = curr;
    }

    curr.NextSong = halfway;
    Console.WriteLine(start.IsRepeatingPlaylist());
}