【问题标题】:get loops in a linked list C#在链表 C# 中获取循环
【发布时间】:2013-02-19 13:43:12
【问题描述】:

我有一个程序可以像这样在 c# 中创建一个链表:

class Point
{
    public string Name { get; set; }
    public List<Point> NextPoints { get; set; }

    public Point()
    {
        NextPoints = new List<Point>();
    }
}

这是具有名称和下一个点的点对象。

我用数据填充一个点列表,

List<Point> Points;

我在这里定义了一条线:

class DashedLine
{
    public Point X { get; set; }
    public Point Y { get; set; }

}

我需要一个递归函数来获取给定 DashedLine

的循环

这样我传递了 DashedLine 对象,该函数返回一个构成循环的点列表。

请帮我做这个功能。

【问题讨论】:

  • 您应该使用所有对象的列表(在您的情况下最好使用排序的),或者使用链表(将下一个对象存储在对象本身中)。把它们混在一起听起来是个坏主意
  • 我只看到一些课程。导致问题的函数在哪里?
  • 如果一个点有一个点列表,它就不再是一个列表,它要么是树,要么是图。
  • 确实,它应该有对下一个 Point 对象的引用,或者只是属于下一个 Point 自然为 index+1 的 Points 列表中
  • 除了你的数据结构,你希望如何从一行中得到一个循环?给定一个示例 DashedLine,您能否给出预期的输出?

标签: c# data-structures singly-linked-list


【解决方案1】:

考虑改变你的数据结构,可能是这样的:

class Program
{
    static void Main(string[] args)
    {
        DashedLine line = new DashedLine();
        line.Points.Add(new Point { X = 1, Y = 1 });
        line.Points.Add(new Point { X = 2, Y = 2 });
        line.Points.Add(new Point { X = 3, Y = 3 });
        line.Points.Add(new Point { X = 4, Y = 4 });

        foreach (Point p in line.Points)
        {
            Debug.WriteLine("Point {0}, {1}", p.X, p.Y);
        }
    }
}

class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

class DashedLine
{
    public List<Point> Points { get; set; }

    public DashedLine()
    {
        Points = new List<Point>();
    }
}

输出:

Point 1, 1
Point 2, 2
Point 3, 3
Point 4, 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多