双向循环链表打印字母

2020/01/04 102

算法 循环链表

要求实现用户输入一个数使26个字母的排列发生变化。例如用户输入 3 或 29,输出结果:DEFGHIJKLMNOPQRSTUVWXYZABC,同时需要支持负数,例如用户输入-3 或 -29,输出结果:XYZABCDEFGHIJKLMNOPQRSTUVW,要求支持 int 范围内的数字。

class Program
{
    static void Main(string[] args)
    {
        var letter = GetLetterChain();
        while (true)
        {
            Console.Write("请输入一个整数:");
            if (int.TryParse(Console.ReadLine(), out int number))
            {
                var cursor = letter;
                if (number >= 0)
                {
                    for (int i = 0; i < number; i++)
                    {
                        cursor = cursor.Next;
                    }
                }
                else
                {
                    for (int i = number; i < 0; i++)
                    {
                        cursor = cursor.Prior;
                    }
                }

                var start = cursor;
                while (true)
                {
                    Console.Write(cursor.Value);
                    cursor = cursor.Next;
                    if (cursor == start)
                    {
                        Console.WriteLine();
                        break;
                    }
                }
            }
            else
            {
                Console.WriteLine("输入有误");
            }
        }
    }

    static Letter GetLetterChain()
    {
        int start = 'B';
        int end = 'Z';
        Letter letterA = new Letter('A');
        Letter prior = letterA;
        for (int i = start; i <= end; i += 2)
        {
            var letter = new Letter((char)i)
            {
                Prior = prior
            };
            prior.Next = letter;
            prior = letter;
            if (i + 1 < end)
            {
                var next = new Letter((char)(i + 1))
                {
                    Prior = prior
                };
                prior.Next = next;
                prior = next;
            }
        }
        prior.Next = letterA;
        letterA.Prior = prior;
        return letterA;
    }
}

class Letter
{
    public char Value { get; set; }
    public Letter Next { get; set; }
    public Letter Prior { get; set; }

    public Letter(char value)
    {
        Value = value;
    }
}
评论