2

位置层次结构的数据结构或数据模型

I have the following location types,

Airport
City
State
Country

Hierarchy is Country has a state, State has a City and a City has airport.

City:San Francisco To City:Frankfort    Rate is 100$ is stored in the system in some form.

当有人询问从 Airport:SFO 到 Airport:FRA 的费率时,应用程序应该查找从 Airport:SFO 到 Airport:FRA 的任何可用费率。

由于我们没有(我们只有城市到城市),应用程序应该检查比机场高一级的城市。因此,应用程序应该能够找到 City of Airport:SFO 和 City of Airport:Frankfort,并检查是否有可用的费率。在这种情况下,它获得 100 美元,因为城市:旧金山到城市:法兰克福的汇率保持为 100 美元。

如何在数据结构中表示这个位置层次结构(在 Java 中)?图或树有用吗?如果可以,请给我一些样品。

4

2 回答 2

0

您可以尝试一些树结构,如下所示

优点

1.跨不同位置类型的统一数据结构。

2.添加新的位置类型不需要新的类。

3.parent查找变得容易。

4.recursive traversal of parent 成为可能。

5.孩子的递归遍历成为可能。

public class Location
{
    private LocationType locationType;
    private Set<Location> children = new HashSet<Location>();
    private Location parent;

    public int rateTo(Location location)
    {
        int rate = -1;

        Location from = this;
        Location to = location;

        do
        {
            rate = getRate(from, to);
            if (rate > -1)
                break;

            from = from.parent;
            to = to.parent;

            if (from == null || to == null)
                break;
        } while (true);

        return rate;
    }

    public void addChildLocation(Location child)
    {
        child.parent = this;
        children.add(child);
    }

    public int getRate(Location from, Location to)
    {
        //1. implement your own database lookup, etc......
        //2. take care of reverse location parameters also...
        return -1;
    }

    public enum LocationType
    {
        Airport,
        City,
        State,
        Country
    }
}
于 2013-05-14T14:30:51.770 回答
0

IMO,有两种自下而上或自上而下的方式(尽管两者实际上都是基于 HAS-A 关系:

自下而上:

1、有类 Airport, City, State , Country

2、 Airport 有 City,City 有 State,State 有 Country 变量

现在,只要您想要价格,您就可以转到 Airport 对象,检查 City->State->Country 等并相应收费

自顶向下:

1、有类Country、State、City、Airport

2、Country会有一个包含State的List,State会有List of City,City会有Airport List

我更喜欢第一个,因为维护父级的 1 个值比维护所有子级的列表更容易/有效。

于 2013-05-14T09:36:35.610 回答